katang
katang

Reputation: 2774

Why -fPIC must be provided as definition, rather than compiler flag

In my CmakeLists.txt file I have had the line

  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wall")

and with that, I run into the error

"You must build your code with position independent code if Qt was built with -reduce-relocations. " "Compile your code with -fPIC (-fPIE is not enough)."

Then I accidentally found topic

Error while compiling QT project in cmake

where it was suggested to add the line

add_definitions(-fPIC)

And really, it seems to work. I have two questions:

1./ Is something wrong with the first form of defining PIC? (or, why they have different effect?)

2./ I did "reprocess" that line from and older project, where it worked fine. What could change?

Upvotes: 3

Views: 1119

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

The line add_definitions(-fPIC) is wrong. First, it should be add_compile_options. Then, add_definition is a directory command which you should avoid.

CMake must detect that the macro name starts with -f and add it as compiler option instead.

What you really want is to tell CMake that a target should be compiled as position independent code.

set_target_properties(your-executable PROPERTIES
    POSITION_INDEPENDENT_CODE ON
)

That should do the trick and is compiler agnostic.

Upvotes: 3

Related Questions