nonForgivingJesus
nonForgivingJesus

Reputation: 593

CMAKE: Build executable and library and link them

I use CMake for building and want to keep my project flexible and consice, so I decided to group code files in separate folders. But in src folder i have subfolder with code i want separate into library. I made CMakeLists.txt where i want code to compile, but CMake throws error.

I've read this question and answers didn't help. I think i messed up somewhere else (or solution is a bit dated)

Here is my catalog tree:

uint32-sort/
├── build
├── CMakeLists.txt           $1 // Main build file, for whole project
├── include                     // Headers folder
│   ├── file_manager.hpp
│   └── sort_container.hpp
└── src                         // Source folder
    ├── main.cpp        
    └── sort_lib                // Lib source folder
    ├── CMakeLists.txt       $2 // Build file for lib
        ├── file_manager.cpp
        └── sort_container.cpp

CMakeLists.txt $1 :

cmake_minimum_required(VERSION 3.15)

SET(PROJECT_NAME "Uint32Sort")
project(${PROJECT_NAME} VERSION 0.01 LANGUAGES CXX)


include_directories(${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src)
add_executable(uint32sort main.cpp)
add_subdirectory(${PROJECT_SOURCE_DIR}/src/sort_lib/)


target_link_libraries(${PROJECT_NAME} SortCore)

set_target_properties(${PROJECT_NAME} PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED ON)

CMakeLists.txt $2 :

cmake_minimum_required(VERSION 3.1.0)

SET(PROJECT_NAME "SortCore")
project(${PROJECT_NAME} VERSION 0.01 LANGUAGES CXX)

include_directories(${PROJECT_SOURCE_DIR}/../../include ${PROJECT_SOURCE_DIR})

file(GLOB SRC_LIB_FILES *.cpp)

add_library(${PROJECT_NAME} ${SRC_LIB_FILES})
target_link_libraries(${PROJECT_NAME} openmp)

set_target_properties(${PROJECT_NAME} PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED ON)

I expected to run cmake .. in uint32-sort/build folder and get executable linked with library from uint32-sort/src/sort_lib/ but everything what i get is this error:

CMake Error at CMakeLists.txt:12 (target_link_libraries):
  Cannot specify link libraries for target "Uint32Sort" which is not built by
  this project.

Upvotes: 0

Views: 5842

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41840

Just as the error says: you have no target named Uint32Sort. You have however a target named uint32sort:

#              v---------- executable target
add_executable(uint32sort main.cpp)

So your target_link_libraries call should use the target as its first parameter:

# use PRIVATE of no public header use SortCore
target_link_libraries(uint32sort PUBLIC SortCore)

Upvotes: 2

Related Questions