0

我正在尝试从使用 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)
4

0 回答 0