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

标签 c++ python-3.x ubuntu g++

我正在尝试制作一个 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/

相关文章:

python - tensorflow 中实现的 sigmoid 函数和从头实现的有什么区别

python - 使用函数迭代处理列表

python-3.x - 从 Cloud Functions 中的父目录或同级目录导入模块?

c++ - 我可以将 std::array 转换为切片吗?或者还有什么我可以用的吗?

c++ - 如果我中断调试,Visual Studio 会释放内存吗?

c++ - C++ 中的连通分量标记

c++ - strlen 未在此范围内声明 - C++

vim - 在 Vim 中恢复删除的行?

c - 奇怪的 OpenCV 距离变换结果

c++ - 黑莓 10 : GNU STL