Brad
Brad

Reputation: 10660

CMake - Depending on another cmake project

I have the following structure to a project I am working on:

---Library1
------build
------include
------src
------CMakeLists.txt
---Library2
------build
------include
------src
------CMakeLists.txt
---Executable1
------build
------include
------src
------CMakeLists.txt

Library1 is a library I am developing that needs to link with Library2 which is a 3rd party library. When I build Library1, I need it to automatically build Library2 and link with it. Executable1 will need to build and link with Library1. I'm not sure how to do with with Cmake, and I was wondering if anyone could guide me in the right direction. I think I may need to use the add_dependencies command or add_subdirectory but I'm not sure how to go about using them and making sure they are linked to my library. Any help would be appreciated.

Upvotes: 9

Views: 18153

Answers (1)

Fraser
Fraser

Reputation: 78320

I'd think the best commands here are likely to be add_subdirectory (as you suspected) and target_link_libraries.

I guess with your directory structure, I'd expect to see a "top-level" CMakeLists.txt in the root. In that CMake file, you'd invoke the subdirectories' CMakeLists using add_subdirectory.

I imagine both Library1 and Library2 are actual CMake targets, included via add_library, and similarly you have add_executable(Executable1 ...). In this case, you can add the following to Library1/CMakeLists.txt:

target_link_libraries(Library1 Library2)

CMake now automatically links Library2 whenever Library1 is specified as a dependency. If Library2 is modified, then it will be rebuilt automatically before being linked to Library1 again.

Likewise in Executable1/CMakeLists.txt you can then do:

target_link_libraries(Executable1 Library1)

Probably the only thing to watch for here is that the order of the add_subdirectory commands would need to be

add_subdirectory(Library2)
add_subdirectory(Library1)
add_subdirectory(Executable1)

so that the dependencies are defined before they're referred to in the target_link_libraries calls.

A final point which seems odd to me is that you have a build directory per target. Normally there should only be a need for a single build directory (preferably outside the source tree).

Upvotes: 10

Related Questions