QLibrary无法解析共享库中的函数

时间:2014-12-10 21:24:05

标签: c++ qt5 qlibrary

我试图从使用Qt创建的共享库中动态包含函数。我使用QLibrary来做到这一点。但我有以下问题:当我尝试调用QLibrary :: resolve()方法时,它总是返回0.。

这是我的共享库的头文件 qtarithmetic.h

#ifndef QTARITHMETIC_H
#define QTARITHMETIC_H

#include <QtCore/qglobal.h>

#if defined(QTARITHMETIC_LIBRARY)
#  define QTARITHMETICSHARED_EXPORT Q_DECL_EXPORT
#else
#  define QTARITHMETICSHARED_EXPORT Q_DECL_IMPORT
#endif

class QTARITHMETICSHARED_EXPORT Qtarithmetic
{

public:
    Qtarithmetic();
    int add(int, int);
    int sub(int, int);
};

#endif // QTARITHMETIC_H

这是我共享库的cpp文件 qtarithmetic.cpp

#include "qtarithmetic.h"

Qtarithmetic::Qtarithmetic() {}

extern "C" QTARITHMETICSHARED_EXPORT int Qtarithmetic::add(int a, int b) {
    return a + b;
}

extern "C" QTARITHMETICSHARED_EXPORT int Qtarithmetic::sub(int a, int b) {
    return a - b;
}

这是使用我的库的测试项目的 .pro 文件:

QT       += core

QT       -= gui

TARGET = qt-arithmetic-use
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

这是此测试项目的 .cpp 文件:

#include <QCoreApplication>
#include <QProcess>
#include <QString>
#include <QTextStream>
#include <QDebug>
#include <QLibrary>

int main() {
    QTextStream out(stdout);
    int a = 0, b = 0, r1 = 0, r2 = 0;
    a = 3; b = 4;

    QLibrary library("/home/danil/build-qt-arithmetic-Desktop-Debug/libqt-arithmetic.so");
    if (!library.load())
        out << library.errorString() << endl;
    if (library.load())
        out << "library loaded" << endl;

    typedef int (*MyPrototype)(int, int);

    MyPrototype myFunction = (MyPrototype)library.resolve("add");
    if (myFunction)
        r1 = myFunction(a,b);
    else
        out << library.errorString() << endl;

    MyPrototype myFunction2 = (MyPrototype)library.resolve("sub");
    if (myFunction2)
        r2 = myFunction2(a,b);
    else
        out << library.errorString() << endl;

    out << r1 << " " << r2 << endl;

    return 0;
}

library.errorString()包含以下信息:

Cannot resolve symbol "add" in /home/danil/build-qt-arithmetic-Desktop-Debug/libqt-arithmetic.so: (/home/danil/build-qt-arithmetic-Desktop-Debug/libqt-arithmetic.so: undefined symbol: add)
Cannot resolve symbol "sub" in /home/danil/build-qt-arithmetic-Desktop-Debug/libqt-arithmetic.so: (/home/danil/build-qt-arithmetic-Desktop-Debug/libqt-arithmetic.so: undefined symbol: sub)

0 个答案:

没有答案