CMAKE 中添加 -fPIC 编译器选项的惯用方法是什么?

2021-12-26 00:00:00 c cmake c++

我遇到了至少 3 种方法来做到这一点,我想知道哪种是惯用的方法.这几乎对任何静态库都需要完成.我很惊讶 CMake 中的 Makefile 生成器不会自动将它添加到静态库中.(除非我遗漏了什么?)

I've come across at least 3 ways to do this and I'm wondering which is the idiomatic way. This needs to be done almost universally to any static library. I'm surprised that the Makefile generator in CMake doesn't automatically add this to static libraries. (unless I'm missing something?)

target_compile_options(myLib PRIVATE -fPIC)

add_compile_options(-fPIC)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fpic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpic")

我相信可能还有其他变化.(如果你找到了,请编辑我的问题)

I believe there might also be other variations. (please edit my question if you find one)

如果您碰巧知道这个问题的答案,您是否也知道是否有一种方法可以在不修改其 CMakeLists.txt 文件的情况下使用此标志编译 3rd 方 CMake 项目?我遇到过缺少该标志的静态库.将静态库编译为动态库时会导致问题.

If you happen to know the answer to this question, do you also know if there is a way to cause a 3rd party CMake project to be compiled with this flag without modifying its CMakeLists.txt file? I have run across static libraries missing that flag. It causes problems when compiling a static library into a dynamic library.

你得到:

relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC

推荐答案

您可以在所有目标上设置位置无关代码属性:

You can set the position independent code property on all targets:

set(CMAKE_POSITION_INDEPENDENT_CODE ON)

或在特定库中:

add_library(lib1 lib1.cpp)
set_property(TARGET lib1 PROPERTY POSITION_INDEPENDENT_CODE ON)

参考:CMAKE_POSITION_INDEPENDENT_CODE cmake 构建系统

相关文章