C++ CMAKE 中添加 -fPIC 编译器选项的惯用方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38296756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the idiomatic way in CMAKE to add the -fPIC compiler option?
提问by 010110110101
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?)
我遇到了至少 3 种方法来做到这一点,我想知道哪种是惯用的方法。这几乎对任何静态库都需要完成。我很惊讶 CMake 中的 Makefile 生成器不会自动将它添加到静态库中。(除非我遗漏了什么?)
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)
我相信可能还有其他变化。(如果你找到一个,请编辑我的问题)
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.
如果您碰巧知道这个问题的答案,您是否也知道是否有一种方法可以在不修改其 CMakeLists.txt 文件的情况下使用此标志编译 3rd 方 CMake 项目?我遇到过缺少该标志的静态库。将静态库编译为动态库时会导致问题。
You get:
你得到:
relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
回答by Amadeus
You can set the position independent code property on all targets:
您可以在所有目标上设置位置无关代码属性:
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
or in a specific library:
或在特定库中:
add_library(lib1 SHARED lib1.cpp)
set_property(TARGET lib1 PROPERTY POSITION_INDEPENDENT_CODE ON)
Reference: CMAKE_POSITION_INDEPENDENT_CODEcmake build system