我编写了一个使用第三方共享库的共享库mylib1,在我的例子中是libtinyxml2(对于这个问题,第三方库是不相关的:它可以是任何库)。我写了一个应用程序,它依赖于。构建app1成功,但构建mylib1失败,这可能是因为链接器在链接mylib1时没有被告知链接到app1。我错过了什么?[I][~/Programs/cmake-jenkins/big_proj/src/build]$ make[ 25%] Building CXX object mylib1/CMakeFiles/mylib1.dir/src/my_functions.cpp.o[ 50%] Linking CXX shared library libmylib1.so[ 50%] Built target mylib1[ 75%] Building CXX object app1/CMakeFiles/app1.dir/src/main.cpp.o[100%] Linking CXX executable app1../mylib1/libmylib1.so: undefined reference to `tinyxml2::StrPair::Reset()'../mylib1/libmylib1.so: undefined reference to `tinyxml2::StrPair::~StrPair()'collect2: error: ld returned 1 exit statusmake[2]: *** [app1/CMakeFiles/app1.dir/build.make:97: app1/app1] Error 1make[1]: *** [CMakeFiles/Makefile2:402: app1/CMakeFiles/app1.dir/all] Error 2make: *** [Makefile:84: all] Error 2文件夹结构.├── app1│ ├── CMakeLists.txt│ ├── src│ │ ├── include│ │ │ └── functions_p.hpp│ │ └── main.cpp├── CMakeLists.txt└── mylib1 ├── CMakeLists.txt ├── src │ ├── include │ │ └── my_functions.hpp │ └── my_functions.cpp./CMakeLists.txt# Top level CMakeLists.txtcmake_minimum_required(VERSION 3.8.2)add_subdirectory(app1)add_subdirectory(mylib1)app1/CMakeLists.txt文件project("app1" CXX)set(APP1_SOURCE_FILES src/main.cpp )add_executable(app1 ${APP1_SOURCE_FILES})target_include_directories(app1 PRIVATE src/include)target_link_libraries(app1 mylib1)mylib1/CMakeLists.txt文件project("lib1" CXX)find_library(TINYXML_LIB tinyxml2 REQUIRED)set(MYLIB1_SOURCE_FILES src/my_functions.cpp )set(MYLIB_INCLUDE_FILES src/include/my_functions.hpp)add_library(mylib1 SHARED ${MYLIB1_SOURCE_FILES} ${MYLIB1_INCLUDE_FILES} )target_include_directories(mylib1 PUBLIC src/include)# I have checked that TINYXML_LIB is set, so the library IS found.target_link_libraries(mylib1 PUBLIC ${TINYXML_LIB})libtinyxml2输出显示库对有依赖关系,并且该文件在我的系统上作为app1存在。[I][~/Programs/cmake-jenkins/big_proj/src/build]$ readelf -d mylib1/libmylib1.soDynamic section at offset 0x16cd0 contains 29 entries: Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libtinyxml2.so.6] 0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6] 0x0000000000000001 (NEEDED) Shared library: [libm.so.6] 0x0000000000000001 (NEEDED) Shared library: [libgcc_s.so.1] 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] 0x000000000000000e (SONAME) Library soname: [libmylib1.so]在详细模式下运行生成的readelf表明,确实当链接libtinyxml2.so.6时,它不会链接到/usr/lib/libtinyxml2.so.6:[ 75%] Linking CXX executable app1cd /home/danb/Programs/cmake-jenkins/big_proj/src/build/app1 && /usr/bin/cmake -E cmake_link_script CMakeFiles/app1.dir/link.txt --verbose=1/usr/bin/c++ CMakeFiles/app1.dir/src/main.cpp.o -o app1 -Wl,-rpath,/home/danb/Programs/cmake-jenkins/big_proj/src/build/mylib1 ../mylib1/libmylib1.so (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 在链接最终应用程序时解析外部引用,因此在target_link_libraries中包含libtinyxml2。 (adsbygoogle = window.adsbygoogle || []).push({});
09-06 19:49