问题
I want to rebuild a simple application based on a .cpp, a .h and multiple .so files. From what i've seen, my CMakeLists.txt should be like this :
cmake_minimum_required(VERSION 3.5)
set(CMAKE_CXX_STANDARD 11)
project(test C CXX)
add_executable(${PROJECT_NAME} main.cpp)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_SOURCE_DIR}/lib)
target_link_libraries(test ${CMAKE_SOURCE_DIR}/libA.so ${CMAKE_SOURCE_DIR}/libB.so)
All files are in the same folder. I previously linked my .cpp with my .h file correctly. cmake .
is giving me no error, but after using make
i get :
main.cpp:(.text+0xf2d) : undefined reference to « pthread_create »
Which is a function that doesn't belong to my .h file so it should be in the .so file. I don't know if the issue comes from the link or the file .so itself.
I also have file with the same name like libA.so, libA.so.0 or libA.so.0.2, should i include all of these files in my executable ?
回答1:
The error message means that you have to add pthread
to the list of linked libraries. In target_link_libraries
you only list the library names without path, lib
prefix and file extension:
cmake_minimum_required(VERSION 3.5)
set(CMAKE_CXX_STANDARD 11)
project(test C CXX)
find_package(Threads REQUIRED)
add_executable(${PROJECT_NAME} main.cpp)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_SOURCE_DIR}/lib)
target_link_libraries(test A B Threads::Threads)
You can add paths with target_link_directories:
cmake_minimum_required(VERSION 3.5)
set(CMAKE_CXX_STANDARD 11)
project(test C CXX)
find_package(ThreadsREQUIRED)
add_executable(${PROJECT_NAME} main.cpp)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_SOURCE_DIR}/lib)
target_link_directories(test PRIVATE ${CMAKE_SOURCE_DIR})
target_link_libraries(test PRIVATE A B Threads::Threads)
回答2:
The good way to do it is to define respective target which will represent library.
add_library(externalLibA SHARED IMPORTED)
set_target_properties(externalLibA
PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/libA.so)
target_include_directories(externalLibA
INTERFACE ${CMAKE_SOURCE_DIR}/lib)
Then add this target as dependency of your target.
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC externalLibA)
来源:https://stackoverflow.com/questions/65886495/how-to-link-so-files-with-cmake