我正在编写一个使用CMake的库,并按照以下说明尝试将Abseil链接到其中:

https://github.com/abseil/abseil-cpp/blob/master/CMake/README.md

我的CMakeLists.txt基本上包含:

add_library(MyLib SHARED src/mylib.cc)
add_subdirectory(third_party/abseil-cpp)
target_link_libraries(MyLib PRIVATE absl::base absl::strings absl::str_format)


现在,如果我编译库,则会出现以下错误:

/usr/bin/ld: third_party/abseil-cpp/absl/strings/libabsl_absl_str_format_internal.a(arg.cc.o): relocation R_X86_64_PC32 against symbol `_ZNKSt17basic_string_viewIcSt11char_traitsIcEE4sizeEv' can not be used when making a shared object; recompile with -fPIC


换句话说,CMake无需使用位置无关代码即可编译Abseil。然后,我尝试找乐子,看看将图书馆改为静态图书馆会发生什么。将CMakeLists.txt更改为

add_library(MyLib STATIC src/mylib.cc)
add_subdirectory(third_party/abseil-cpp)
target_link_libraries(MyLib PRIVATE absl::base absl::strings absl::str_format)


运行cmake时出现以下错误:

CMake Error: install(EXPORT "MyLibTargets" ...) includes target "MyLib" which requires target "absl_base" that is not in the export set.
CMake Error: install(EXPORT "MyLibTargets" ...) includes target "MyLib" which requires target "absl_strings" that is not in the export set.
CMake Error: install(EXPORT "MyLibTargets" ...) includes target "MyLib" which requires target "absl_str_format" that is not in the export set.


我是CMake的新手,但我还没有弄清楚如何解决这两个错误。您如何在CMake中传递性地指定应编译依赖项以定位独立的代码?

最佳答案

this thread on GitHub


  好像您想使用@Mizux先前建议的CMAKE_POSITION_INDEPENDENT_CODE。
  将set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)添加到您的CMakeLists.txt文件[...]


这应该可以解决在构建共享库时仍然看到的所有问题,同时仍然可以将Abseil静态地链接到库中。

关于c++ - Abseil和CMake在库中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58976823/

10-11 20:57