Issue
I'm trying to compile C++ code with python embedded in it. The compiler does not compile my code with '-fPIE' flag even though I've added it in CMakeList.txt. Here's my CMakeList:
cmake_minimum_required(VERSION 3.3)
project(TestCython)
add_executable(main main.cpp)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-result -Wsign-compare -g -fdebug-prefix-map=/build/python3.8-6QL2k7/python3.8-3.8.2=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O3 -Wall -fPIE")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-result -Wsign-compare -g -fdebug-prefix-map=/build/python3.8-6QL2k7/python3.8-3.8.2=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O3 -Wall -fPIE")
# Eigen
find_package(Eigen3 3.3 REQUIRED NO_MODULE)
# Embedded Python Includes
include_directories(/usr/include/python3.8
/usr/include/eigen3/ )
# Embedded Python Linker
link_directories(/usr/lib/python3.8/config-3.8-x86_64-linux-gnu
/usr/lib)
target_link_libraries( main
python3.8
crypt
pthread
dl
util
m )
set(CMAKE_C_COMPILER gcc)
set(CMAKE_CXX_COMPILER g++)
If I run the generated make file, it will report a lot of similar errors and ask me to recompile with '-fPIE', like this one: /usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/libpython3.8.a(call.o): relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a PIE object; recompile with -fPIE
The compilation succeeds if I don't use cmake:
g++ -I/usr/include/python3.8 -Wno-unused-result -Wsign-compare -g -fdebug-prefix-map=/build/python3.8-6QL2k7/python3.8-3.8.2=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O3 -Wall -fPIE main.cpp -o main -L/usr/lib/python3.8/config-3.8-x86_64-linux-gnu -L/usr/lib -lpython3.8 -lcrypt -lpthread -ldl -lutil -lm
Cmake version is 3.16.3. Python version is 3.8.2. System is Ubuntu 20.04 How can I solve those errors?
Solution
Note that most of the time this error has nothing to do with the PIE
flag but is rather something else screwy about your build, unfortunately it’s a bit hard to tell because your CMake config is a bit screwy.
This particular error however is probably because you’re setting your properties incorrectly; Setting CMAKE_CXX_FLAGS
and similar variables does nothing if you do it after defining your target with add_executable
. This can be avoided entirely by using a more modern CMake style (out of scope for this answer, just google Modern CMake for some examples), in this particular case instead of setting flags on those variables you could for example do
target_compile_options(main PRIVATE -fpie)
Answered By - Cubic