How do I correctly create dependencies between tar

2019-01-22 06:44发布

问题:

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)

回答1:

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)


回答2:

It is not exactly clear what you want to do, and why Project and Depency have to be build separately.

My first though on your example would be

  1. In PROJECT, CMakeLists.txt

    • Remove add_dependencies(Project Dependency) There is no need to specify dependency, target_link_libraries() already does that.
  2. In DEPENDENCY, CMakeLists.txt

    • Remove project(Dependency) It builds a library, so why to have own project ?
    • Remove target_link_libraries(Dependency) Because it does nothing


标签: c++ build cmake