Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link CMake subprojects with one another

Tags:

c++

cmake

I would like to link projects that are added via add_subproject with one another. Suppose i have a project structure like this:

(root)
 I--exec
    I--"some source files"
    I--CMakeLists.txt
 I--lib
    I--"some source files"
    I--CMakeLists.txt
 I--CMakeLists.txt

Is there some way i can have my root level CMakeLists.txt just sort-of as a workspace file? So it behaves like a .sln from Visual Studio?

I tried this, to give you an idea of what i mean:

cmake_minimum_required(VERSION 2.8)
project(test)

add_subdirectory(exec)
add_subdirectory(lib)

target_link_libraries(exec lib)
target_include_directories(exec lib/include)

Obviously, it threw a config error at the second last line, stating that i cannot do that because exec is not built by this file (the current CMakeLists.txt?). Is there some way to achive what i want to do?

like image 756
tubberd Avatar asked Jan 06 '23 00:01

tubberd


1 Answers

For CMake >= 2.8.10, the usage of target_link_libraries and target_include_directories is incorrect.

They should specify the target SYSTEM|BEFORE|PUBLIC|INTERFACE|PRIVATE; prefixed by LINK_ on target_link_libraries.

As a side-note, just for clear dependency management (IMHO):

In your root CMakeLists.txt there should be no target_link_libraries nor target_include_directories, they should be in the subproject. So your root CMakeLists, for example, should be:

cmake_minimum_required(VERSION 2.8)
project(test)

add_subdirectory(lib)
add_subdirectory(exec)

In your exec/CMakeLists.txt:

add_executable (exec main.cpp)

target_link_libraries (exec LINK_PUBLIC lib)
target_include_directories (exec PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/../lib)

In your lib/CMakeLists.txt:

add_library (lib libmain.cpp)

target_include_directories (lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

I'm not sure if it makes a difference, but I use the add_subdirectory for the library before the executable.

like image 139
Bruno Ferreira Avatar answered Jan 15 '23 19:01

Bruno Ferreira