Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed Python in C++ (using CMake)

Tags:

c++

python

cmake

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?

like image 469
Dark_Phoenix Avatar asked Apr 15 '26 16:04

Dark_Phoenix


1 Answers

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)
like image 101
SpacePotatoes Avatar answered Apr 18 '26 05:04

SpacePotatoes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!