如何将.so文件与CMake链接 [英] how to link .so files with CMake
问题描述
我想基于.cpp,.h和多个.so文件重建一个简单的应用程序.从我所看到的,我的CMakeLists.txt应该是这样的:
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)
所有文件都在同一文件夹中.之前,我已将.cpp与.h文件正确链接. cmake.
没有给我任何错误,但是使用 make
后,我得到了:
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 »
哪个函数不属于我的.h文件,因此它应该位于.so文件中.我不知道问题是否来自链接或文件.so本身.
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.
我也有同名的文件,例如libA.so,libA.so.0或libA.so.0.2,我应该在可执行文件中包含所有这些文件吗?
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 ?
推荐答案
该错误消息表示您必须将 pthread
添加到链接库的列表中.在 target_link_libraries
中,您仅列出没有路径, lib
前缀和文件扩展名的库名称:
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)
您可以使用 target_link_directories
添加路径a>:
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)
这篇关于如何将.so文件与CMake链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!