当我尝试在 Windows 上使用 g++ 编译我的 C++ 项目时遇到问题
代码:
#include <python.h>
int main(int argc, char **argv)
{
Py_Initialize();
PyRun_SimpleString("print('Hello World!')");
Py_Finalize();
return 0;
}
我正在使用这个命令:
g++ -I C:\Python310\include main.cpp -o output -L C:\Python310\libs -lpython310
它总是给我这个关于未定义引用的错误:
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
您正在尝试链接使用 Windows 编译的程序
g++
(x86_64-w64-mingw32-g++.exe
)
针对使用 Micosoft MSVC 构建的导入库 C:/Python310/libs/python310.lib
。
这是行不通的,因为 x86_64-w64-mingw32
库与 MSVC 库不兼容。
获取 MSYS2 的 x86_64-w64-mingw32
python 库
并使用其头文件和库进行构建。
考虑安装和使用MSYS2 作为您在 Windows 上的工作
gcc/g++
环境。