Home > Blockchain >  CMake: Cannot link to a static library in a subdirectory
CMake: Cannot link to a static library in a subdirectory

Time:08-24

I have the following folder structure in my c project

*--build
|---(building cmake here)
|
*--main.cpp
|
*--CMakeLists.txt (root)
|
*--modules
|---application
|------app.h
|------app.cpp
|------CMakeLists.txt

And the code below for both CMakeLists.txt files:

CMakeLists.txt (module)

cmake_minimum_required(VERSION 3.15.2)
file(GLOB APPLICATION_HEADERS *.h *.hpp)
file(GLOB APPLICATION_SRC *.c *.cpp)

add_library(app_lib STATIC
            ${APPLICATION_HEADERS} 
            ${APPLICATION_SRC})

target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR})

CMakeLists.txt (root)

cmake_minimum_required(VERSION 3.15.2)

project(main)
enable_language(C CXX)

#set directories 
set(CMAKE_BINARY_DIR build)
set(CMAKE_CONFIGURATION_TYPES UNIX)
set(CMAKE_MODULES_DIR ${SOURCE_DIR}/cmake)

add_executable(${PROJECT_NAME} main.cpp)

# Build sub-modules
include_directories(modules/application)
add_subdirectory(modules/application)

find_library(MY_APP_LIB app_lib REQUIRED)

target_link_libraries(${PROJECT_NAME} PUBLIC ${MY_APP_LIB})

However, when I do cmake .. in my build directory, it seems like my app library just doesn't build and it doesn't link to it. I end up with the following error:

CMake Error at CMakeLists.txt:80 (find_library):
  Could not find MY_APP_LIB using the following names: app_lib

I tried looking at other stackoverflow questions but it seems like I'm missing something. Any help is appreciated!

Thanks!

CodePudding user response:

You don't need to use find_* to locate the library. In fact you cannot locate the library this way, since find_library searches the file system for the library during configuration, i.e. before anything gets compiled.

There's good news though: If the targets are created in the same cmake project, you can simply use the name of the cmake target as parameter for target_link_libraries:

...
add_library(app_lib STATIC
            ${APPLICATION_HEADERS} 
            ${APPLICATION_SRC})

# note: this should be a property of the library, not of the target created in the parent dir
target_include_directories(app_lib PUBLIC .)
...
add_subdirectory(modules/application)

target_link_libraries(${PROJECT_NAME} PUBLIC app_lib)

CodePudding user response:

You don't need to do find_library for your own targets, just link directly to app_lib:

target_link_libraries(${PROJECT_NAME} PUBLIC app_lib)
  • Related