Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

CMake build target without specifying target_include_directories

I have a project with the following file layout:

Project
├── CMakeLists.txt
├── app
│   ├── CMakeLists.txt
│   └── main.cpp
└── ext
    ├──CMakeLists.txt
    └── lib
        ├── CMakeLists.txt
        ├── include
        │   └── foo.h
        └── foo.cpp

foo is a 3rd party library that I downloaded the source code of that I want to use in main.cpp. I can build main.cpp using a cmake file like:

add_executable(app main.cpp)

target_include_directories(app PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/extern/foo/include)
target_link_libraries(app foo)

However I feel it should be the responsibility of the foo lib to specify what files should be included when using it. Is there a way to make this work without the target_include_directories call?


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

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

Just add

target_include_directories(foo PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)

into extern/foo/CMakeLists.txt.

That way the include directory will be accessible when you build foo library and for anyone who links with that library.


Note, that automatic propagation of include directory and other library properties works only when you link with the library target:

# Assuming you have 'add_library(foo)' somewhere,
# PUBLIC and INTERFACE properties of the `foo` library will be propagated
# to the 'app'.
target_link_libraries(app PUBLIC foo)

This would work even if add_library(foo) is issued after target_link_libraries call.

Propagation won't work when link with the library file:

# Propagation won't work with a name of the library file:
target_link_libraries(app PUBLIC foo.a)
# Propagation won't work with a full path to the library file:
target_link_libraries(app PUBLIC /path/to/foo.a)
# If 'add_library(foo)' in inaccessible from the project,
# then linking with 'foo' means linking with a library file,
# so propagation won't work.
target_link_directories(app PUBLIC /path/to/)
target_link_libraries(app PUBLIC foo)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...