在 C++ 中嵌入 Python(使用 CMake)

Embed Python in C++ (using CMake)

我正在尝试 运行 一个 python C++ 脚本。例如:

// main.cpp
#include <python3.10/Python.h>
int main(int argc, char* argv[])
{
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is',ctime(time()))\n");
    Py_Finalize();
    return 0;
}

我有这样的 CMakeLists:

// CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
project(task_01)

SET(CMAKE_CXX_FLAGS "-O0")
SET(CMAKE_C_FLAGS "-O0")

set(CMAKE_CXX_STANDARD 20)

find_package (Python COMPONENTS Interpreter Development)
find_package(PythonLibs 3.10 REQUIRED)
include_directories ( ${PYTHON_INCLUDE_DIRS} )

add_executable(task_01 main.cpp)

但我遇到编译错误(我使用 CLion IDE):

undefined reference to `Py_Initialize'
undefined reference to `PyRun_SimpleStringFlags'
undefined reference to `Py_Finalize'

我对 运行 python 脚本做错了什么?

CMakeLists.txt中的这些配置帮助了我:

cmake_minimum_required(VERSION 3.21)
project(task_01)

SET(CMAKE_CXX_FLAGS "-O0")
SET(CMAKE_C_FLAGS "-O0")

set(CMAKE_CXX_STANDARD 20)

find_package (Python REQUIRED
        COMPONENTS Interpreter Development)

add_executable(task_01 main.cpp Utility.h Utility.cpp Sort.h Sort.cpp)

target_include_directories(${PROJECT_NAME} PRIVATE
        ${Python_INCLUDE_DIRS})

target_link_directories(${PROJECT_NAME} PRIVATE
        ${Python_LIBRARY_DIRS})

target_link_libraries(${PROJECT_NAME} PRIVATE
        ${Python_LIBRARIES})

首选导入目标 (https://cmake.org/cmake/help/latest/module/FindPython.html#imported-targets):

cmake_minimum_required(VERSION 3.18)
project(task_01)

find_package(Python REQUIRED Development)

add_executable(task_01 main.cpp Utility.cpp Sort.cpp)
target_link_libraries(task_01 PRIVATE Python::Python)