Я встраиваю Python в проект C++ с помощью примера кода из https://docs.python.org/3/extending/emb ... -embedding:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(python_in_cpp)
set(CMAKE_CXX_STANDARD 11)
# sudo apt install libpython3.11-dev
find_package(PythonLibs 3.11 REQUIRED)
find_package(Python COMPONENTS Interpreter Development)
message("Python_FOUND:${Python_FOUND}")
message("Python_VERSION:${Python_VERSION}")
message("Python_Development_FOUND:${Python_Development_FOUND}")
message("Python_LIBRARIES:${Python_LIBRARIES}")
include_directories(${Python_INCLUDE_DIRS})
link_directories(
${Python3_LIBRARY_DIRS}
${Python3_RUNTIME_LIBRARY_DIRS}
)
link_libraries(${Python3_LIBRARIES})
add_executable(python_in_cpp main.cpp)
main.cpp:
#define PY_SSIZE_T_CLEAN
#include
int
main(int argc, char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
return 0;
}
Журнал CMake показывает, что оба Python и PythonLibs найдены, но при компиляции я получил ошибки по нескольким неопределенным ссылкам:
main.cpp:(.text+0x1f): undefined reference to `Py_DecodeLocale'
/usr/bin/ld: main.cpp:(.text+0x63): undefined reference to `Py_SetProgramName'
/usr/bin/ld: main.cpp:(.text+0x68): undefined reference to `Py_Initialize'
/usr/bin/ld: main.cpp:(.text+0x7c): undefined reference to `PyRun_SimpleStringFlags'
/usr/bin/ld: main.cpp:(.text+0x81): undefined reference to `Py_FinalizeEx'
/usr/bin/ld: main.cpp:(.text+0x9e): undefined reference to `PyMem_RawFree'
Как мне исправить это для сборки этого проекта?
У меня установлено несколько Python:
$ apt list --installed | grep "lib*python"
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
libpython3-dev/stable,now 3.11.2-1+b1 amd64 [installed]
libpython3-stdlib/stable,now 3.11.2-1+b1 amd64 [installed,automatic]
libpython3.11-dev/stable-security,now 3.11.2-6+deb12u3 amd64 [installed]
libpython3.11-minimal/stable-security,now 3.11.2-6+deb12u3 amd64 [installed,automatic]
libpython3.11-stdlib/stable-security,now 3.11.2-6+deb12u3 amd64 [installed,automatic]
libpython3.11/stable-security,now 3.11.2-6+deb12u3 amd64 [installed,automatic]
Подробнее здесь: https://stackoverflow.com/questions/790 ... codelocale