C++找不到 python 库.代码阻止GNU GCC

C++ python library not found. Code Blocks GNU GCC

本文关键字:GNU GCC 代码 找不到 python C++      更新时间:2023-10-16

所以这是我第一次尝试在C++程序中使用 python,我在链接库时遇到了一些问题。

所以我将代码块IDE与GNU GCC编译器一起使用,我有以下主程序:

#include <Python.h>
#include <iostream>
using namespace std;
int main()
{
    cout<<"starting interpreter."<<endl;
    Py_Initialize();
    PyRun_SimpleString("print 'Im in python!'");
    Py_Finalize();
    return 0;
}

我的链接设置如下(在编译器和调试器设置的代码块 GUI 中):

linker settings:
    link libraries:
        C:Python27libslibpython27.a
search directories:
    linker:
        C:Python27libs

我错过了什么吗?还是我这样做的方式错误了?

构建消息:

C:Usersusers_nameDesktopPythonIntegratedTestmain.cpp|1|error: Python.h: No such file or directory|
C:Usersusers_nameDesktopPythonIntegratedTestmain.cpp||In function 'int main()':|
C:Usersusers_nameDesktopPythonIntegratedTestmain.cpp|9|error: 'Py_Initialize' was not declared in this scope|
C:Usersusers_nameDesktopPythonIntegratedTestmain.cpp|10|error: 'PyRun_SimpleString' was not declared in this scope|
C:Usersusers_nameDesktopPythonIntegratedTestmain.cpp|11|error: 'Py_Finalize' was not declared in this scope|

错误消息显示Python.h: No such file or directory 。这意味着,编译器找不到请求的文件。搜索目录中的路径不正确。需要包含的头文件通常位于名为 include 的目录中。对于Windows上的Python,这在你的情况下C:Python27include

在 CodeBlocks 中,可以在 Settings - Compiler and debugger - Search directories - Compiler 下修改包含搜索目录。

完成此操作后,您将获得对错误的未定义引用。错误消息告诉您,您在代码中使用了一个函数,编译器找不到其实现,而只能找到声明(在头文件中)。

该实现可以在源文件或静态库中提供。Windows 上的 CPython 带有预构建的静态库。它位于您的案例中C:Python27libspython26.lib

在更改它之后,编译应该会成功。

main.cpp|1|error: Python.h: No such file or directory

是一个编译时错误,因为编译器在包含搜索路径中找不到 Python.h。 如果你在命令行上使用gcc,我会告诉你指定Python安装的包含文件夹,如下所示:

-I/path/to/Python27/include

(在我的Windows Python 2.7安装上,它的C:Python27include

我不确定您将如何在 CodeBlock 中执行此操作,但肯定有一种方法可以指定您的"标头包含路径"。

请注意,这与"库搜索路径"或"链接器搜索路径"不同 - 它专门用于编译器和标头搜索位置。