g++ - Python.h:没有这样的文件或目录

g++ - Python.h: No such file or directory

本文关键字:文件 Python g++      更新时间:2023-10-16

我正在尝试制作一个C++脚本来运行一些简单的Python代码:

// t.cpp
#include <Python.h>
int main(int argc, char* argv[])
{
Py_Initialize();
PyRun_SimpleString("print('TEST PASSED')");
Py_Finalize();
return 0;
}

运行g++ t.cpp时,出现错误:

t.cpp:1:20:致命错误:Python.h:没有这样的文件或目录

编译已终止

我发现了许多类似的问题,都是特定于IDE或其他开发软件的,或者通过安装python3-dev来解决。python3-dev包已经安装,我什至尝试在尝试编译时手动包含标头:

g++ t.cpp -I ~/.virtualenvs/MainEnv/include/python3.5m/Python.h
g++ t.cpp -I /usr/include/python3.5m/Python.h

两者都没有改变任何东西。

如何修复此错误?

更新:我发现使用g++ t.cpp -I /usr/include/python3.5/似乎包含标头,但随后它遇到了更多错误:

t.cpp:(.text+0x10(:对"Py_Initialize"的未定义引用

t.cpp:(.text+0x1f(:对"PyRun_SimpleStringFlags"的未定义引用

t.cpp:(.text+0x24(:对"Py_Finalize"的未定义引用

collect2:错误:ld 返回 1 个退出状态

我已经在我的github上设置了一个类似的例子

g++ t.cpp缺少一些东西:

  • 告诉 g++ cpython 的标头在哪里(通过-I/path/to/headers/(
  • 告诉 g++ 链接到 libpython (通过-lpython3.5m(

您还可以使用pkg-config检索这些标志

$ pkg-config python-3.5 --libs --cflags
-I/usr/include/python3.5m -I/usr/include/x86_64-linux-gnu/python3.5m -lpython3.5m

您的命令行应如下所示g++ -I/usr/include/python3.5m t.cpp -lpython3.5m

#include <...>适用于编译器附带的包含。
#include "Python.h"用于任何其他包含。

运行以下命令来编译代码:

我的测试.cpp

#include <Python.h>
int main(int argc, char* argv[])
{
Py_Initialize();
PyRun_SimpleString("print('TEST PASSED')");
Py_Finalize();

return 0;
}

编译

$ g++ mytest.cpp `pkg-config python3-embed --libs --cflags` -o mytest
$ ./mytest