Home > front end >  Embed Python in C (using CMake)
Embed Python in C (using CMake)

Time:05-09

I'm trying to run a python script in c . For example:

// 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;
}

And I have such 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)

But I get compile errors (I use CLion IDE):

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

What am I doing wrong to run a python script?

CodePudding user response:

Such configurations in CMakeLists.txt helped me:

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})

CodePudding user response:

Prefer imported targets (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)
  • Related