Including Python.h in Qt application causes undefi

2019-05-15 11:30发布

I'd like to include Python.h (from the Python distribution in my Anaconda folder) in my project to call a python script. The program compiles fine when I don't include python. But as soon as I do, I get undefined reference errors to functions implemented in Qt classes (so not my own functions!). The python version I'd like to include is 3.5.5.

The part that confuses me most is undefined reference to QJsonValue::toString(). This method is implemented inline so how can its implementation not be found? According to QtCreator the problem originates in a compiled object that tries to call this function.

This is a minimally (not) working example:

The .pro file:

QT -= gui
CONFIG += c++11 console no_keywords
SOURCES += main.cpp
INCLUDEPATH += {path to python include}
LIBS += -L{path to python lib} -lpython3.5m

And the main.cpp file:

#include <Python.h>
#include <QCoreApplication>
#include <QJsonValue>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    PyObject *obj;
    QJsonValue value;
    value.toString();
    return a.exec();
}

Update: It seems like including Python from Anaconda is causing the issue. When I remove LIBS += -L{path to python lib} -lpython3.5m it compiles just fine. And when I remove INCLUDEPATH += {path to python include} but keep the other line I get the following error:

/{user}/build-TestProject-Qt_5_9-Debug/TestProject: /{user}/anaconda3/lib/libQt5Core.so.5: version `Qt_5.9' not found (required by /{user}/build-TestProject-Qt_5_9-Debug/TestProject)

1条回答
你好瞎i
2楼-- · 2019-05-15 12:18

The issue was caused by using Anaconda's Python distribution. Setting the project to include Python causes QtCreator to use Anaconda's qmake instead of the installed version. If you can live with Qt 5.6, which is the current version of Qt in Anaconda, create a Kit with Anaconda's qmake and the program compiles again.

If you need a newer version of Qt you can add the line

-L/{user}/Qt5.9.5/5.9.5/gcc_64/lib -lQt5Core

to your .pro file. Adjust it to your Qt version and what libraries you need. This is not exactly a pretty solution, as you need to adjust the .pro file whenever you want to switch versions, but it's the only solution I know of.

查看更多
登录 后发表回答