【发布时间】:2020-10-06 09:41:47
【问题描述】:
我正在尝试编译嵌入了 python 的 C++ 代码。即使我已将其添加到 CMakeList.txt 中,编译器也不会使用“-fPIE”标志编译我的代码。这是我的 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++)
如果我运行生成的make文件,它会报很多类似的错误,并要求我用'-fPIE'重新编译,比如这个: /usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/libpython3.8.a(call.o) :在制作 PIE 对象时,不能使用针对 `.rodata.str1.8' 的重定位 R_X86_64_32;使用 -fPIE 重新编译
不使用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 版本是 3.16.3。 Python 版本是 3.8.2。系统是 Ubuntu 20.04 我该如何解决这些错误?
【问题讨论】:
-
为什么要设置所有这些变量?这不是推荐的方式,例如cmake.org/cmake/help/v3.1/command/target_compile_features.html为什么要在CMake中设置编译器?
-
不建议手动设置
CMAKE_C_FLAGS和CMAKE_CXX_FLAGS中的标志,但如果你真的必须这样做,你应该在调用add_executable()之前设置它们。你真的应该在target_compile_options中设置这些标志。
标签: python c++ linux cmake g++