【问题标题】:g++ - Python.h: No such file or directoryg++ - Python.h:没有这样的文件或目录
【发布时间】:2017-12-13 15:19:37
【问题描述】:

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

// 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): undefined reference to `Py_Initialize'

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

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

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

【问题讨论】:

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


    【解决方案1】:

    #include &lt;...&gt; 用于编译器附带的包含。
    对任何其他包含使用 #include "Python.h"

    【讨论】:

    • Python.h 周围的尖括号和引号都会产生相同的错误。
    • C++ 标准对&lt;...&gt;"..." 的含义非常模糊。
    【解决方案2】:

    我已经建立了一个类似的例子on my 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

    【讨论】:

    • 我在“更新”下提到添加-I 标志似乎正确地包含了标题,但遇到了更多错误。 -lpython3.5-lpython3 返回 /usr/bin/ld: cannot find -lpython3(.5)
    • 啊,在ubuntu上是-lpython3.5m
    • 当然,我被淘汰了 1 个字母。非常感谢,现在完美运行!
    【解决方案3】:

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

    mytest.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
    

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2021-09-19
      相关资源
      最近更新 更多