CMAKE中添加-fPIC编译器选项的惯用方法是什么? [英] What is the idiomatic way in CMAKE to add the -fPIC compiler option?

查看:11586
本文介绍了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)

如果您碰巧知道此问题的答案,您还知道是否有办法导致第三方CMake项目要使用此标志编译而不修改其CMakeLists.txt文件?我跑过静态库缺少那个标志。当将静态库编译为动态库时,会导致问题。

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


推荐答案

属性:

set(CMAKE_POSITION_INDEPENDENT_CODE ON)

或在特定库中:

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

参考: CMAKE_POSITION_INDEPENDENT_CODE cmake build system

这篇关于CMAKE中添加-fPIC编译器选项的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆