从C++调用Python,如何消除`-Wstrict-prototypes`警告?

4 投票
1 回答
1608 浏览
提问于 2025-04-18 10:47

我正在尝试从C++调用Python函数。我写了一个简单的 main.cpp 文件和一个 helloworld.py 文件,内容如下:

main.cpp:

int main(int argc, char* argv[])
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    PyObject *pModule = PyImport_ImportModule( "helloworld" );

    PyObject *pFunc = PyObject_GetAttrString(pModule, "say_hello_world");

    PyEval_CallObject(pFunc, NULL);

    Py_Initialize();
}

helloworld.py:

def say_hello_world():
    print( "Hello World from Python" )

我用以下命令编译这个程序:

g++ `python-config --cflags` main.cpp `python-config --ldflags` -o main

结果一切正常,除了我收到了以下警告:

cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]

这是什么原因呢?有没有办法解决这个问题?

1 个回答

1

写一个脚本 gccflags-filter,这个脚本的作用是过滤掉不适合某种编程语言的标志(flags)。举个例子:

  python-config --cflags | gccflags-filter --lang=c++

这些标志的列表可以从相关的文档中找到。

如果你现在需要一个临时的解决办法来处理你遇到的问题,可以考虑使用类似下面的方式:

 g++ `python-config --cflags | sed s/-Wstrict-prototypes//`

撰写回答