I have problem when i try to compile my c++ project using g++ on windows
The code:
#include <python.h>
int main(int argc, char **argv)
{
Py_Initialize();
PyRun_SimpleString("print('Hello World!')");
Py_Finalize();
return 0;
}
I am using this command:
g++ -I C:\Python310\include main.cpp -o output -L C:\Python310\libs -lpython310
And it always gives me this error about undefined references:
AppData\Local\Temp\ccQdtubj.o:main.cpp:(.text+0x1f): undefined reference to `_imp__Py_DecodeLocale'
AppData\Local\Temp\ccQdtubj.o:main.cpp:(.text+0x6c): undefined reference to `_imp__Py_SetProgramName'
AppData\Local\Temp\ccQdtubj.o:main.cpp:(.text+0x73): undefined reference to `_imp__Py_Initialize'
AppData\Local\Temp\ccQdtubj.o:main.cpp:(.text+0x8d): undefined reference to `_imp__PyRun_SimpleStringFlags'
AppData\Local\Temp\ccQdtubj.o:main.cpp:(.text+0x94): undefined reference to `_imp__Py_FinalizeEx'
AppData\Local\Temp\ccQdtubj.o:main.cpp:(.text+0xb5): undefined reference to `_imp__PyMem_RawFree'
collect2.exe: error: ld returned 1 exit status
You are attempting to link a program compiled with Windows
g++(x86_64-w64-mingw32-g++.exe) against an import libraryC:/Python310/libs/python310.libthat was built with Micosoft MSVC. That will not work becausex86_64-w64-mingw32libraries are incompatible with MSVC libraries. Get thex86_64-w64-mingw32python library for MSYS2 and build using its header files and libraries.Consider installing and using MSYS2 as your working
gcc/g++environment on Windows.With that environment, a compile-and-link commandline (using the Windows filesystem) ought be like:
or:
An import library in the msys64 environment is not called
name.libas per Windows butlibname.dll.a,C:\msys64\mingw64\lib\libpython3.dll.abeing for example the import library forC:\msys64\mingw64\bin\libpython3.dllLater
@MatyVymlátil commented:
It turns out that
PyRun_SimpleStringFlagsis undefined inlibpython3.dll.abut is defined inlibpython3.11.dll.a. Assuming (which appears to be true) that you have extended yourPATHwithC:\msys64\mingw64\bin;C:\msys64\mingw64\x86_64-w64-min\bin, you can check things like this in Powershell like:in contrast with:
Or in the MSYS2 shell ( = Linux bash) like:
See the nm manual
That means you have to use the first command for a successful linkage. In Powershell
Or in MSYS2 shell:
That warning:
will happen if you do not have the environment variables
PYTHONHOMEandPYTHONPATHset (correctly) in your the shell environment in whichoutput.exeis launched or more specifically the spawned environment is which your program calls python.You can set those variables and make the warning go away. In Powershell:
Or in MSYS2 shell:
And of course you can set these variables permanently in the Windows settings for your user profile or the system profile.
You could also set those environment variables in your program itself before calling
Py_Initialize, but that would be unduly hard-coded.