Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Linking to static python lib #343

Open
@RoelVugts

Description

@RoelVugts

Hi,

I succesfully built python as a static library with python-cmake-buildsystem. Now i want my c++ program to link to it and execute python code. I built a simple test program to see if it works:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main()
{
    Py_Initialize();
    PyRun_SimpleString("print('Hello World')");
    Py_Finalize();

    return 0;
}

This is my error:

====================[ Build | pyCMake | Release ]===============================
"C:\Program Files\JetBrains\CLion 2023.1.2\bin\cmake\win\x64\bin\cmake.exe" --build C:\Users\roelv\Documents\pyCmake\cmake-build-release --target pyCMake -j 14
[1/2] Building CXX object CMakeFiles\pyCMake.dir\main.cpp.obj
[2/2] Linking CXX executable pyCMake.exe
FAILED: pyCMake.exe 
main.cpp.obj : error LNK2019: unresolved external symbol __imp_PyRun_SimpleStringFlags referenced in function main
main.cpp.obj : error LNK2019: unresolved external symbol __imp_Py_Initialize referenced in function main
main.cpp.obj : error LNK2019: unresolved external symbol __imp_Py_Finalize referenced in function main
pyCMake.exe : fatal error LNK1120: 3 unresolved externals
ninja: build stopped: subcommand failed.

I see that Py_initialize() is implemented in the file pylifecycle.c and it looks like this file gets compiled in the python39 static library file. So I don't understand why the linker is not able to find the implementation. Is there something i am doing wrong?

Here is my CMakeLists.txt file:

project(pyCMake)

CMAKE_MINIMUM_REQUIRED(VERSION 3.5)

set(CMAKE_CXX_STANDARD 11)

include_directories(python-cmake-buildsystem/python-install/include)
link_directories(python-cmake-buildsystem/python-install/libs)

add_executable(pyCMake main.cpp)

target_link_libraries(pyCMake PUBLIC python39)

My goal is eventually to compile python as a static library in my executable so when distributing my program the user does not have to install python.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions