我正在尝试在C ++中运行python代码
#include <python3.7/Python.h>
// PYTHON START
Py_Initialize();
PyObject *module_name = PyUnicode_FromString("plotter");
PyObject *module = PyImport_Import(module_name);
Py_DECREF(module_name);
if (module != nullptr) {
PyObject *py_function = PyObject_GetAttrString(module, "plot_data");
//call the python and pass the data generated in C
//------------------------------------------------------------------------------------------------------
if (py_function && PyCallable_Check(py_function)) {
pid_t pid = fork();
if (pid == 0) {
PyObject *res = PyObject_CallFunctionObjArgs(py_function, q);
}
}
}
我以前从未做过此事,但我认为这不是问题,因为我无法构建代码。 我的错误是:
/snap/clion/81/bin/cmake/linux/bin/cmake --build /home/alex/Workspace/Clion/krpc/cmake-build-debug --target krpc -- -j 2
[ 50%] Linking CXX executable krpc
/usr/bin/ld: CMakeFiles/krpc.dir/test.cpp.o: in function `main':
/home/alex/Workspace/Clion/krpc/test.cpp:43: undefined reference to `PyUnicode_FromString'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/krpc.dir/build.make:85: krpc] Error 1
make[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/krpc.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/krpc.dir/rule] Error 2
make: *** [Makefile:118: krpc] Error 2
我的cmake文件如下:
cmake_minimum_required(VERSION 3.14)
project(krpc)
set(CMAKE_CXX_STANDARD 11)
link_libraries("-lkrpc -lprotobuf -lpthread")
find_package(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_DIRS})
add_executable(krpc test.cpp)
target_link_libraries(krpc ${PYTHON_LIBRARIES})
编辑:我的cmake输出如下:
/snap/clion/81/bin/cmake/linux/bin/cmake -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - Unix Makefiles" /home/alex/Workspace/Clion/krpc
-- PYTHON_LIBRARIES: /usr/lib/x86_64-linux-gnu/libpython2.7.so
-- Configuring done
-- Generating done
-- Build files have been written to: /home/alex/Workspace/Clion/krpc/cmake-build-debug
[Finished]
我已经在cmake中查看了find_packages(),如果我只有普通的python,它会找到python2.7,但我想要3.7。我似乎找不到我想要的东西。
答案 0 :(得分:1)
您的链接器试图在libpython.so中找到PyUnicode_FromString。它是Python2,没有PyUnicode_FromString(只有非Unicode PyString_FromString)。
CMakeLists.txt示例:
cmake_minimum_required(VERSION 3.14)
project(krpc)
set(CMAKE_CXX_STANDARD 11)
link_libraries("-lkrpc -lprotobuf -lpthread")
add_executable(krpc test.cpp)
target_link_libraries(krpc python3.7m)
答案 1 :(得分:0)
将所需的cmake更改为版本3.7.2,然后清除项目的缓存后,此问题已解决。