Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c++ - What is the idiomatic way in CMAKE to add the -fPIC compiler option?

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)

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.

You get:

relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 lib1.cpp)
set_property(TARGET lib1 PROPERTY POSITION_INDEPENDENT_CODE ON)

Reference: CMAKE_POSITION_INDEPENDENT_CODE cmake build system


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...