What is the idiomatic way in CMAKE to add the -fPIC compiler option?(CMAKE 中添加 -fPIC 编译器选项的惯用方法是什么?)
问题描述
我遇到了至少 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 构建系统
这篇关于CMAKE 中添加 -fPIC 编译器选项的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CMAKE 中添加 -fPIC 编译器选项的惯用方法是什么?
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
