解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作

How to fix: 'can not be used when making a shared object; recompile with -fPIC' using Cmake. Using plain g++ works

本文关键字:Cmake -fPIC 使用 工作 g++ with shared not be can 方法      更新时间:2023-10-16

我收到一条消息"创建共享对象时无法使用;使用 -fPIC 重新编译"

我尝试了其他示例,问题是一样的。

我试过了

  • 从模块更改为共享
  • cmake .. -DCMAKE_CXX_FLAGS=-fPIC
  • 和其他变体

这有效:

c++ -c -fPIC -I/usr/include/python3.6m ../account.cpp
c++ -shared -Wall -Werror -Wl,--export-dynamic account.o -L/usr/local/lib -lboost_python36 -o account.so

这是基本的cmake

cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(Test)
find_package(PythonInterp REQUIRED)
find_package(PythonLibs ${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR} EXACT REQUIRED)
find_package(Boost 1.70.0 COMPONENTS python REQUIRED)
add_library(account SHARED account.cpp)
target_link_libraries(account Boost::python)
target_include_directories(account PRIVATE ${PYTHON_INCLUDE_DIRS})
set_target_properties(account PROPERTIES PREFIX "")

使用:使 VERBOSE=1 输出命令为:

c++  -DBOOST_ALL_NO_LIB -Daccount_EXPORTS -I/usr/include/python3.6m -isystem /usr/local/include  -fPIC   -o CMakeFiles/account.dir/account.cpp.o -c /src/boost_python_example/account.cpp
c++ -fPIC   -shared -Wl,-soname,account.so -o account.so CMakeFiles/account.dir/account.cpp.o /usr/local/lib/libboost_python36.a

所以 cmake 没有得到相同的路径和标志,我正在学习 cmake,所以我试图理解这个问题。显然,问题不在于实际的库,而在于告诉cmake在哪里可以找到合适的库。

解决方案非常简单。比较两个命令 cmake 命令缺少的是: --export-dynamic

所以我使用选项(BUILD_SHARED_LIBS"构建共享库而不是静态库"(解决了足够有趣的评论,需要评论。

工作解决方案:

cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(Test)
option(BUILD_SHARED_LIBS "Build libraries as shared as opposed to static" ON)
find_package(PythonInterp REQUIRED)
find_package(PythonLibs ${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR} EXACT REQUIRED)
find_package(Boost 1.70.0 COMPONENTS python REQUIRED)
add_library(account SHARED account.cpp)
target_link_libraries(account Boost::python)
target_include_directories(account PRIVATE ${PYTHON_INCLUDE_DIRS})
set_target_properties(account PROPERTIES PREFIX "")

感谢大家的评论,他们引导我找到解决方案