greywolf82
greywolf82

Reputation: 22173

CMake target with sibling folders

My project structure is the following:

root
-CMakeLists.txt
----exec
-----CMakeLists.txt
-----src
------a.cpp
------a.h
----lib
-----CMakeLists.txt
-----src
------b.cpp
-----inc
------b.h

Exec target depends on lib target. My main CMakeLists.txt is just the following:

cmake_minimum_required(VERSION 2.8)
cmake_policy(SET CMP0048 NEW)
project(FOO CXX)
add_subdirectory(lib)
add_subdirectory(exec)

In the CMakeLists.txt of the library I use add_library() and I use add_executable() in the exec folder. The problem is that the executable can't find the library and I don't know how to say in the exec CMakeLists.txt that another target exist called lib which is a library to use. I think I'm missing something in the project configuration.

Lib CmakeLists.txt

cmake_minimum_required(VERSION 2.8)

cmake_policy(SET CMP0048 NEW)
project(BASIC CXX)

add_library(BASIC src/b.cpp)

set(HEADERS_FILE_DIRS inc)

include_directories(${HEADERS_FILE_DIRS})

#Linking
target_link_libraries(BASIC pthread)

Exec CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

cmake_policy(SET CMP0048 NEW)
project(EXEC CXX)

add_executable(EXEC src/a.cpp)

set(HEADERS_FILE_DIRS src ${CMAKE_CURRENT_SOURCE_DIR}/../lib/inc)

include_directories(${HEADERS_FILE_DIRS})

set_target_properties(EXEC PROPERTIES OUTPUT_NAME "EXEC")

find_library(BASIC_LIBRARY BASIC HINTS <ABS PATH HERE>/lib)
#Linking
target_link_libraries(EXEC pthread ${BASIC_LIBRARY})

Upvotes: 1

Views: 2071

Answers (1)

Kevin
Kevin

Reputation: 18243

As commented, you can simply link the BASIC CMake library target. Because it was created earlier in the same CMake invocation, CMake already know of its existence and will link it properly.

In addition, (if you can upgrade your CMake to at least 2.8.11) you can apply the lib/inc include directory directly to your BASIC library target using target_include_directories. Use the PUBLIC scoping argument here to propagate these include directories to consuming CMake targets. This way, you can avoid mentioning the lib/inc directory in your exec/CMakeLists.txt file altogether:

In lib/CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

cmake_policy(SET CMP0048 NEW)
project(BASIC CXX)

add_library(BASIC src/b.cpp)

set(HEADERS_FILE_DIRS inc)

# Assign this include directory to the target as a build AND usage requirement.
target_include_directories(BASIC PUBLIC ${HEADERS_FILE_DIRS})

# Linking
target_link_libraries(BASIC PUBLIC pthread)

In exec/CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

cmake_policy(SET CMP0048 NEW)
project(EXEC CXX)

add_executable(EXEC src/a.cpp)

set(HEADERS_FILE_DIRS src)

include_directories(${HEADERS_FILE_DIRS})

set_target_properties(EXEC PROPERTIES OUTPUT_NAME "EXEC")

# Linking BASIC to EXEC, which propagates the 'lib/inc' include directory
# and the 'pthread' library linkage to EXEC also.
target_link_libraries(EXEC PRIVATE BASIC)

Upvotes: 2

Related Questions