0

I am trying to compile a c++ project referencing Python using CMake. I am using Cygwin and I have Python2.7 source files in Cygwin.

For example:

PyObject *l = PyList_New(0);

Online help suggested I add the -lpython2.7 linker flag. Am I not adding this correctly in CMake? Otherwise why can I still not use the Python library and how might I fix this?

The compile line:

C:\cygwin64\bin\cmake.exe --build "C:\Users\...\.clion10\system\cmake\generated\3e6845d6\3e6845d6\Release" --target projectname -- -j 4

The CMakeList.txt file:

cmake_minimum_required(VERSION 2.8.4)
project(projectname)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -lpython2.7")

set(SOURCE_FILES
    src/cpp/...
    src/cpp/...
    src/cpp/..
    src/cpp/...
    src/cpp/...)

add_executable(projectname ${SOURCE_FILES})

The errors...

CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaeb4): undefined reference to `PyDict_New'
CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaeb4): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `PyDict_New'
CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaec4): undefined reference to `PyList_New'
CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaec4): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `PyList_New'
CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaf0d): undefined reference to `PyDict_New'
CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaf0d): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `PyDict_New'
CMakeFiles/spot.dir/src/cpp/OBwrapper.cpp.o:OBwrapper.cpp:(.text+0xaf25): undefined reference to `PyString_FromString'

...and so on....
4

1 回答 1

4

你误解了 CMake 的方式:在使用之前你应该找到它!即确保构建包所需的一切都在构建主机上可用和可用。否则,浪费(编译)时间(比如 2 小时)然后得到一个找不到某些头文件/库/可执行文件的错误是不好的。因此,在 CMake 运行时,您最好确保您需要的一切都在这里。为此,CMake 有很多工具。

考虑您的特殊情况:您需要找到 Python 库,否则无法构建。为此,您应该find_package像这样使用:

find_package(PythonLibs REQUIRED)

如果需要,请查看文档并提供其他选项(如版本)。您不应该在您CMakeLists.txt的 . 相反,Python libs finder 模块将提供您以后需要使用的变量,或者如果没有找到任何内容,则会失败并出现错误。

如果 CMake 结束时没有错误,您可以使用找到的 Python 库。首先,您需要更新#include路径:

 include_directories(${PYTHON_INCLUDE_DIRS})

然后告诉链接器您的可执行文件projectname需要与 Python 库链接:

add_executable(projectname ${SOURCE_FILES})
target_link_libraries(projectname ${PYTHON_LIBRARIES})

再一次,尽量避免直接修改CMAKE_CXX_FLAGS(和其他人)——有很多调用可以全局和/或每个目标进行修改。他们之中有一些是:

于 2014-11-16T09:23:52.117 回答