库路径绝对正确并且可以创建所述库的实例,但在调用任何函数时获得“未定义的引用”

问题描述 投票:0回答:2

我正在使用Qt Creator创建一个新项目,我有一个我在Visual Studio中创建的测试“MathLibrary”。我想在我的Qt项目中使用这个库。

我已经搜索了很多个小时来获得我的解决方案的答案,几乎在所有情况下答案都只是库没有被添加到.pro文件中的PATH中。我99%肯定我已经做了一切正确的事,但当我尝试调用这个库中的任何函数时,有些东西导致我得到一个Undefined Reference错误。这是我到目前为止所拥有的。

The library -

MathLibraryH.h:

#pragma once

namespace MathLibrary
{
    class Functions
    {
    public:
        // Returns a + b  
        double Add(double a, double b);

        // Returns a * b  
        double Multiply(double a, double b);

        // Returns a + (a * b)  
        double AddMultiply(double a, double b);
    };
}

MathLibrary.cpp:

#include "stdafx.h"
#include "MathLibraryH.h"

namespace MathLibrary
{
    double Functions::Add(double a, double b)
    {
        return a + b;
    }

    double Functions::Multiply(double a, double b)
    {
        return a * b;
    }

    double Functions::AddMultiply(double a, double b)
    {
        return a + (a * b);
    }
}

The QT project -

test QT project.pro:

    QT       += core gui \
            network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = TestQTProject
TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        mainwindow.cpp \

HEADERS += \
        mainwindow.h \

FORMS += \
        mainwindow.ui

DISTFILES += \
    com_github_msorvig_s3.pri

LIBS += -L$$PWD/../Libs -lMathLibrary

INCLUDEPATH += $$PWD/../Incs

mainwindow.cpp:

#include "MathLibraryH.h"

// .... other stuff ....

void MainWindow::on_btnStage1_clicked()
{
    MathLibrary::Functions lib; // This is just fine
    lib.Add(5, 9); // The "Add" function (or any other function in the library)
                       causes an undefined reference error
}

我还是Qt的新手,但我看不出这些代码有什么问题。

我根据搜索的答案尝试过的其他事情:

将以下代码添加到MathLibrary.h:

#ifdef MATHLIBRARY_EXPORTS  
#define MATHLIBRARY_API __declspec(dllexport)   
#else  
#define MATHLIBRARY_API __declspec(dllimport)   
#endif  

将.pro文件中LIBS声明的格式更改为以下所有内容:

多行:

LIBS += -L$$PWD/../Libs
LIBS += -lMathLibrary

硬编码单行:

LIBS += -LC:\svn\software\WIP\TestQTProject\Libs -lMathsLibrary

我没有做任何工作,我没有其他的想法。

对于它的价值,该库在使用visual studio创建的任何项目中都能正常工作,我尝试创建静态和动态库。

c++ qt reference undefined lib
2个回答
0
投票

MATHLIBRARY_API

在您的类名称前面导出您的dll中的所有公共成员。在导出期间,应设置dllexport部件,并在导入期间使用dllimport部分。

这是一个解释如何从dll导出类的链接:https://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL


0
投票

如果你试图动态链接,问题是您的库MathsLibrary没有导出为动态库,也没有将它作为动态库导入(这就是__declspec(dllexport)所做的,并且宏应该在函数的前面使用或类声明,以产生任何差异)。即使你这样做,也有可能你的编译方式与你的Qt应用程序不同,因此存在链接问题。

但是因为你试图静态链接(我没有在你的代码中看到任何库文件加载),所以问题似乎是你的库和你的Qt应用程序之间的差异。

您应该尝试使用与构建库相同的标志和相同的编译器构建Qt应用程序,反之亦然。如果您的代码按照您的说法工作,它可能会有效。

有关详细信息:

DL Library

How to Create a Plugin Framework

Building plugins using Qt Framework

© www.soinside.com 2019 - 2024. All rights reserved.