I'm using Qt Creator to create a new project, and I have a test "MathLibrary" that I created in Visual Studio. I want to use this library in my Qt project.
I have searched for many hours for an answer to my solution and in almost all cases the answer was simply that the library had not been added to the PATH in the .pro file. I'm 99% sure that I have done everything correct, but something is causing me to get an Undefined Reference error when I try calling any function in this library. Here's what I have so far.
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);
}
}
TestQTProject.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
}
I'm still new to Qt but I can't see what's wrong with any of this code.
Other things I've tried based on answers from searching:
Adding the following code to MathLibrary.h:
#ifdef MATHLIBRARY_EXPORTS
#define MATHLIBRARY_API __declspec(dllexport)
#else
#define MATHLIBRARY_API __declspec(dllimport)
#endif
Changing the format of the LIBS declaration in the .pro file to all of the following:
Multi-line:
LIBS += -L$$PWD/../Libs
LIBS += -lMathLibrary
Hard coded single line:
LIBS += -LC:\svn\software\WIP\TestQTProject\Libs -lMathsLibrary
Nothing I've done works and I have no other ideas left.
For what it's worth, the library works fine in any project created using visual studio, and I've tried creating both a static and dynamic library.
Add
MATHLIBRARY_API
infront of your class name to export all public members in your dll. During export the dllexport part should be set and during import the dllimport part of course.
Here's a link that explains how to export classes from a dll: https://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL