我正在尝试制作一个 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: fatal error: Python.h: No such file or directory
compilation terminated
我发现了很多类似的问题,都是针对某个 IDE 或其他开发软件的,或者是通过安装 python3-dev
解决的。 python3-dev
包已经安装,我什至尝试在尝试编译时手动包含 header :
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/
似乎包含 header ,但随后会遇到更多错误:
t.cpp:(.text+0x10): undefined reference to `Py_Initialize'
t.cpp:(.text+0x1f): undefined reference to `PyRun_SimpleStringFlags'
t.cpp:(.text+0x24): undefined reference to `Py_Finalize'
collect2: error: ld returned 1 exit status
最佳答案
我设置了一个类似的例子 on my github
g++ t.cpp
缺少一些东西:
- 告诉 g++ cpython 的 header 在哪里(通过
-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
关于c++ - g++-Python.h : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002739/