Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c++ - How do I correctly create dependencies between targets in CMake?

I am trying to use CMake to set up some simple dependencies between a C++ project and the libraries that it uses.

The set up is as follows

  • Project
    • Dependency

Project itself contains source files that include headers from Dependency and when the executable is built it needs to be linked against Dependency's static library.

So far I can get this to work, but I have to specify the include directories of Dependency in the CMakeLists.txt file for Project manually. I want this to be pulled out automatically, and I have explored the option of using the find_package() command to do so with limited success and making things much more complicated.

All I want to do is have Dependency built before Project and have Project link against the library and have its include directories. Is there a simple concise way of achieving this?

My current CMake files:

Project, file CMakeLists.txt:

cmake_minimum_required (VERSION 2.6)
project (Project)
include_directories ("${PROJECT_SOURCE_DIR}/Project")
add_subdirectory (Dependency)
add_executable (Project main.cpp)
target_link_libraries (Project Dependency)
add_dependencies(Project Dependency)

Dependency, file CMakeLists.txt:

project(Dependency)
add_library(Dependency SomethingToCompile.cpp)
target_link_libraries(Dependency)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since CMake 2.8.11 you can use target_include_directories. Just simply add in your DEPENDENCY project this function and fill in include directories you want to see in the main project. CMake will care the rest.

PROJECT, CMakeLists.txt:

cmake_minimum_required (VERSION 2.8.11)
project (Project)
include_directories (Project)
add_subdirectory (Dependency)
add_executable (Project main.cpp)
target_link_libraries (Project Dependency)

DEPENDENCY, CMakeLists.txt

project (Dependency)
add_library (Dependency SomethingToCompile.cpp)
target_include_directories (Dependency PUBLIC include)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...