How to create a library with Qt and use it in an application: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
(Misc changes, style)
 
(12 intermediate revisions by 9 users not shown)
Line 1: Line 1:
{{LangSwitch}}
[[Category:HowTo]]
[[Category:HowTo]]
__NOEDITSECTION__
==Introduction==
__NOTOC__


'''English''' [[How_to_create_a_library_with_Qt_and_use_it_in_an_application_Spanish|Español]] [[How_to_create_a_library_with_Qt_and_use_it_in_an_application_Russian|Русский]]
This tutorial illustrates different approaches for using a custom library in your application on Windows. The first part explains how to create a shared library and how to link against it in your application. The second part is about creating and using a static library.
 
== Introduction ==


This tutorial illustrates different approaches for using a custom library in your application on Windows. The first part explains how to create a shared library and how to link against it in your application. The second part is about creating and using a static library.
To organize a bigger project with libraries and executables, take a look at [[SUBDIRS - handling dependencies]]


== Creating a shared library ==
==Creating a shared library==


When creating a shared library that you would like to link against, then you need to ensure that the symbols that are going to be used outside the library are properly exported when the library is created. Subsequently imported when you are linking against the library. This can be done using {{DocLinkAnchor|qtglobal|Q_DECL_EXPORT}} and {{DocLinkAnchor|qtglobal|Q_DECL_IMPORT}} as shown in the following example:
When creating a shared library that you would like to link against, then you need to ensure that the symbols that are going to be used outside the library are properly exported when the library is created. Subsequently imported when you are linking against the library. This can be done using {{DocLink|QtGlobal|Q_DECL_EXPORT}} and {{DocLink|QtGlobal|Q_DECL_IMPORT}} as shown in the following example:


'''test.h'''
'''test.h'''
<syntaxhighlight lang="c++">
#include <QWidget>


<code>
#if defined MAKE_TEST_LIB
#include <QtGui>
    #define TEST_LIB_EXPORT Q_DECL_EXPORT
 
#if defined TEST
#define TEST_COMMON_DLLSPEC Q_DECL_EXPORT
#else
#else
#define TEST_COMMON_DLLSPEC Q_DECL_IMPORT
    #define TEST_LIB_EXPORT Q_DECL_IMPORT
#endif
#endif
 
   
class TEST_COMMON_DLLSPEC Widget : public QWidget
class TEST_LIB_EXPORT Widget : public QWidget
{
{
Q_OBJECT
    Q_OBJECT
public:
public:
  Widget();
    Widget(QWidget *parent = nullptr);
};
};
</code>
</syntaxhighlight>
 
'''test.cpp'''
'''test.cpp'''
 
<syntaxhighlight lang="c++">
<code>
#include <QtGui>
#include "test.h"
#include "test.h"
#include <QtWidgets>


Widget::Widget() : QWidget() {}
Widget::Widget(QWidget *parent) : QWidget(parent) {}
</code>
</syntaxhighlight>


'''test.pro'''
'''test.pro'''


<code>
<syntaxhighlight lang="make">
TEMPLATE = lib
TEMPLATE = lib
# Input
SOURCES += test.cpp
SOURCES += test.cpp
HEADERS += test.h
HEADERS += test.h
DEFINES += TEST
DEFINES += MAKE_TEST_LIB
</code>
QT += widgets
</syntaxhighlight>


In windows, MinGW will output <tt>.a</tt> and <tt>.dll</tt>, MSVC2010 will ouput <tt>.lib</tt> and <tt>.dll</tt>. In linux, MinGW will output <tt>.so</tt>, <tt>.so.1</tt>, <tt>.so.1.0</tt> and <tt>.so.1.0.0</tt> - <tt>.lib</tt>, <tt>.a</tt> and <tt>.so</tt> are import libraries. They help link your code to the library and is needed when you build your file(.a files not all the time).
On Windows, MinGW will output <tt>.a</tt> and <tt>.dll</tt>, MSVC will output <tt>.lib</tt> and <tt>.dll</tt>.
 
On Linux, gcc/clang will output <tt>.so</tt>, <tt>.so.1</tt>, <tt>.so.1.0</tt> and <tt>.so.1.0.0</tt>  
 
<tt>.lib</tt>, <tt>.a</tt> and <tt>.so</tt> are import libraries. They are needed to link your code against the library.


See also the documentation on [http://doc.qt.io/qt-5/sharedlibrary.html Creating Shared Libraries].
See also the documentation on [http://doc.qt.io/qt-5/sharedlibrary.html Creating Shared Libraries].


=== Linking your application against the shared library ===
===Linking your application against the shared library===


In order to use the shared library in your application, then you can include the headers of your library in your code and use the methods. Compile with linking to the .lib file. At runtime this loads the dll which has the implementation.  
In order to use the shared library in your application, you can include the headers of your library in your code and use the methods/classes from there. Also you need to link against the import library file (<tt>.lib</tt>, <tt>.a</tt> and <tt>.so</tt>). At runtime this loads the shared library (<tt>.so.1.0.0</tt> / <tt>.dll</tt>) which has the implementation.  


To set this up, then in your application's .pro file you need to inform the application where to find the headers and the library. The [http://doc.qt.io/qt-5/qmake-variable-reference.html#includepath INCLUDEPATH] needs to point to the directory where the headers are installed, and the [http://doc.qt.io/qt-5/qmake-variable-reference.html#libs LIBS ] variable needs to point to the directory of the .lib file. In addition you need to ensure that the .dll is found by either putting it in the application's directory or in the global <tt>PATH</tt>.  
To set this up, you have to modify your application's .pro file. You need to inform qmake where to find the headers and the library. The [http://doc.qt.io/qt-5/qmake-variable-reference.html#includepath INCLUDEPATH] needs to point to the directory where the headers are installed, and the [http://doc.qt.io/qt-5/qmake-variable-reference.html#libs LIBS] variable needs to point to the directory of the import library file. In addition you need to ensure that the shared library is found by either putting it in the application's directory or in the global <tt>PATH</tt> on windows and the <tt>LD_LIBRARY_PATH</tt> on linux.  


For example:
For example:
Line 66: Line 65:
'''loadTestLib.pro'''
'''loadTestLib.pro'''


<code>
<syntaxhighlight lang="make">
TEMPLATE = app
TEMPLATE = app
TARGET =
TARGET =
Line 72: Line 71:
INCLUDEPATH += ../testLib
INCLUDEPATH += ../testLib
LIBS += -L../testLib/debug -ltestLib
LIBS += -L../testLib/debug -ltestLib
 
#Input
# Input
SOURCES += main.cpp
SOURCES += main.cpp
</code>
</syntaxhighlight>


'''main.cpp'''
'''main.cpp'''


<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtWidgets>
#include "test.h"
#include "test.h"


int main(int argc, char *argv[])
int main(int argc, char *argv[])
{
{
QApplication a(argc, argv);
    QApplication a(argc, argv);
Widget w;
    Widget w;
w.resize(100,100);
    w.resize(100, 100);
w.show();
    w.show();
return a.exec();
    return a.exec();
}
}
</code>
</syntaxhighlight>


alternatively you can right-click your project in Qt Creator and select "Add Library...", choose "External library" and browse for your library file:
alternatively you can right-click your project in Qt Creator and select "Add Library...", choose "External library" and browse for your library file:


* For libraries compiled with MSCV2010 compiler in windows, you look for .lib
*For libraries compiled with MSCV compiler in windows, you look for .lib or .dll
* in Windows, MinGW compiled linking libraries are in .a, but you will need to add it manually (as of Qt Creator 2.7). You could also try simply linking the .dll directly cause it would probably work. Don't try this with a MSCV2010 compiled library.
*On Windows, MinGW compiled linking libraries are in .a, but you will need to add it manually (as of Qt Creator 2.7). You could also try simply linking the .dll directly cause it would probably work. Don't try this with a MSVC compiled library .
* in linux you look for the .so file
*On Linux you look for the .so file


This will append the following code to your *.pro file:
This will append the following code to your *.pro file:


<code>
<syntaxhighlight lang="make">
win32:CONFIG (release, debug|release): LIBS += -L$$PWD/build-MyLibrary/ -lmylibrary
win32:CONFIG (release, debug|release): LIBS += -L$$PWD/build-MyLibrary/ -lmylibrary
else:win32:CONFIG (debug, debug|release): LIBS += -L$$PWD/build-MyLibrary/ -lmylibrary
else:win32:CONFIG (debug, debug|release): LIBS += -L$$PWD/build-MyLibrary/ -lmylibrary
Line 108: Line 106:
INCLUDEPATH += $$PWD/build-MyLibrary
INCLUDEPATH += $$PWD/build-MyLibrary
DEPENDPATH += $$PWD/build-MyLibrary
DEPENDPATH += $$PWD/build-MyLibrary
</code>
</syntaxhighlight>
[http://doc.qt.io/qt-5/qmake-variable-reference.html#pwd $$PWD] is used here to specify the full path leading to the directory containing your .pro file.
[http://doc.qt.io/qt-5/qmake-variable-reference.html#pwd $$PWD] is used here to specify the full path leading to the directory containing your .pro file.


Note that for Unix/Linux systems the library file name is case sensitive, but for Windows you have to leave in all small caps.
Note that for Unix/Linux systems the library file name is case sensitive, but for Windows you have to leave in all lower case.


 
===Using QLibrary to load the shared library===
=== Using QLibrary to load the shared library ===


{{DocLink|QLibrary}} can be used for loading shared libraries at runtime. In this case you only need access to the .dll, access to the headers and .lib file(s) is not necessary.
{{DocLink|QLibrary}} can be used for loading shared libraries at runtime. In this case you only need access to the .dll, access to the headers and .lib file(s) is not necessary.


The following example shows how to set up a library for usage with QLibrary. For the function names to be resolvable, they must be exported as C functions (i.e., without name mangling) from the library. This means that the functions must be wrapped in an extern "C" block if the library is compiled with a C++ compiler.
The following example shows how to set up a library for usage with QLibrary. For the function names to be resolvable, they must be exported as C functions (i.e., without name mangling) from the library. This means that the functions must be wrapped in an <tt>extern "C"</tt> block if the library is compiled with a C++ compiler.


Since we are doing this on Windows we also must explicitly export the function from the DLL using Q_DECL_EXPORT and Q_DECL_IMPORT.
Since we are doing this on Windows we also must explicitly export the function from the DLL using <tt>Q_DECL_EXPORT</tt> and <tt>Q_DECL_IMPORT</tt>.


'''qlibraryLibrary.pro'''
'''qlibraryLibrary.pro'''


<code>
<syntaxhighlight lang="make">
TEMPLATE = lib
TEMPLATE = lib
HEADERS += widget.h
HEADERS += widget.h
SOURCES += widget.cpp
SOURCES += widget.cpp
DEFINES += TEST
DEFINES += MAKE_TEST_LIB
</code>
QT += widgets
</syntaxhighlight>


'''widget.h'''
'''widget.h'''


<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QWidget>


#if defined TEST
#if defined MAKE_TEST_LIB
  #define TEST_COMMON_DLLSPEC Q_DECL_EXPORT
  #define TEST_LIB_EXPORT Q_DECL_EXPORT
#else
#else
  #define TEST_COMMON_DLLSPEC Q_DECL_IMPORT
  #define TEST_LIB_EXPORT Q_DECL_IMPORT
#endif
#endif


extern "C" TEST_COMMON_DLLSPEC QWidget* createWidget1();
extern "C" TEST_LIB_EXPORT QWidget *createWidget1();
</code>
</syntaxhighlight>


'''widget.cpp'''
'''widget.cpp'''


<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtWidgets>
#include "widget.h"
#include "widget.h"


QWidget* createWidget1()
QWidget *createWidget1()
{
{
QWidget *wid = new QWidget();
    QWidget *widget = new QWidget();
wid->resize(100,100);
    widget->resize(100, 100);
return wid;
    return widget;
}
}
</code>
</syntaxhighlight>


=== Loading the library using QLibrary ===
===Loading the library using QLibrary===


To load the library using QLibrary, you can simply pass in the .dll to the QLibrary constructor. Make sure the .dll is available in the application directory or in the global PATH. To use functions from the library in your application, you need to resolve them using {{DocLinkAnchorLbl|QLibrary|resolve|QLibrary::resolve()}}.
To load the library using QLibrary, you can simply pass in the .dll to the QLibrary constructor. Make sure the .dll is available in the application directory or in the global PATH. To use functions from the library in your application, you need to resolve them using {{DocLink|QLibrary|resolve|QLibrary::resolve()}}.


The example below loads the library created above and uses one of its functions to create and show a widget.
The example below loads the library created above and uses one of its functions to create and show a widget.


<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtWidgets>


int main(int argc, charargv)
int main(int argc, char *argv[])
{
{
QApplication app(argc, argv);
    QApplication app(argc, argv);
QLibrary library("qlibraryLibrary.dll");
    QLibrary library("qlibraryLibrary.dll");
if (!library.load())
    if (!library.load())
qDebug() << library.errorString();
        qDebug() << library.errorString();
if (library.load())
    if (library.load())
qDebug() << "library loaded";
        qDebug() << "library loaded";


typedef QWidget*(*CreateWidgetFunction)(void);
    typedef QWidget *(*CreateWidgetFunction)();
CreateWidgetFunction cwf = (CreateWidgetFunction)library.resolve("createWidget1");
    CreateWidgetFunction cwf = (CreateWidgetFunction)library.resolve("createWidget1");
if (cwf) {
    if (cwf) {
  QWidget* wid = cwf();
        QWidget *widget = cwf();
  if (wid) wid->show();
        if (widget)  
} else {
            widget->show();
  qDebug() << "Could not show widget from the loaded library";
    } else {
}
        qDebug() << "Could not show widget from the loaded library";
return app.exec();
    }
    return app.exec();
}
}
</code>
</syntaxhighlight>


== Creating a static library ==
==Creating a static library==


When creating a static library you need to specify the staticlib option to [http://doc.qt.io/qt-5/qmake-variable-reference.html#config CONFIG] in the .pro file. In contrast to the shared library example, you don't need to set up anything special for exporting and importing symbols in your .h file, since the library will be built into the application, for example:
When creating a static library you need to specify the staticlib option to [http://doc.qt.io/qt-5/qmake-variable-reference.html#config CONFIG] in the .pro file. In contrast to the shared library example, you don't need to set up anything special for exporting and importing symbols in your .h file, since the library will be built into the application, for example:
Line 195: Line 194:
'''test.pro'''
'''test.pro'''


<code>
<syntaxhighlight lang="make">
TEMPLATE = lib
TEMPLATE = lib
CONFIG += staticlib
CONFIG += staticlib
 
#Input
# Input
HEADERS += test.h
HEADERS += test.h
SOURCES += test.cpp
SOURCES += test.cpp
</code>
</syntaxhighlight>


=== Using the static library in your application ===
===Using the static library in your application===


Similar to what we did for the shared library loading, you need to set up the [http://doc.qt.io/qt-5/qmake-variable-reference.html#includepath INCLUDEPATH] to point to the directory where the headers are installed and the [http://doc.qt.io/qt-5/qmake-variable-reference.html#libs LIBS] variable to point to the .lib file, for example:
Similar to what we did for the shared library loading, you need to set up the [http://doc.qt.io/qt-5/qmake-variable-reference.html#includepath INCLUDEPATH] to point to the directory where the headers are installed and the [http://doc.qt.io/qt-5/qmake-variable-reference.html#libs LIBS] variable to point to the .lib file, for example:
Line 210: Line 208:
'''useStaticLib.pro'''
'''useStaticLib.pro'''


<code>
<syntaxhighlight lang="make">
TEMPLATE = app
TEMPLATE = app
TARGET =
TARGET =
CONFIG += console
CONFIG += console
 
QT += widgets
# Input
#Input
SOURCES += main.cpp
SOURCES += main.cpp
INCLUDEPATH += ../staticLibrary
INCLUDEPATH += ../staticLibrary
LIBS += -L../staticLibrary/debug -lstaticLibrary
LIBS += -L../staticLibrary/debug -lstaticLibrary
</code>
</syntaxhighlight>


'''main.cpp'''
'''main.cpp'''


<code>
<syntaxhighlight lang="make">
#include <QtGui>
#include "test.h"
#include "test.h"
#include <QtWidgets>


int main(int argc, char *argv[])
int main(int argc, char *argv[])
{
{
QApplication a(argc, argv);
    QApplication a(argc, argv);
Widget w;
    Widget w;
w.resize(100,100);
    w.resize(100, 100);
w.show();
    w.show();
return a.exec();
    return a.exec();
}
}
</code>
</syntaxhighlight>


== Installing a library ==
==Installing a library==


When you build your libraries, it could be useful to have one build for one framework and to centralize them : for example, you could having one library for Android, one for Windows and QT5.4 and one for Windows with Qt5.5 without having specific configurations.
When you build your libraries, it could be useful to have one build for one framework and to centralize them : for example, you could having one library for Android, one for Windows and QT5.4 and one for Windows with Qt5.5 without having specific configurations.
The easiest way is to put your files in the Qt folders by adding in your *.pro file :
The easiest way is to put your files in the Qt folders by adding in your *.pro file :


<code lang="make">
<syntaxhighlight lang="make">
headersDataFiles.path = $$[QT_INSTALL_HEADERS]/MyLib/
headersDataFiles.path = $$[QT_INSTALL_HEADERS]/MyLib/
headersDataFiles.files = $$PWD/src/*.h
headersDataFiles.files = $$PWD/src/*.h
Line 248: Line 246:


libraryFiles.path = $$[QT_INSTALL_LIBS]
libraryFiles.path = $$[QT_INSTALL_LIBS]
Debug:libraryFiles.files = $$OUT_PWD/debug/*.a $$OUT_PWD/debug/*.prl
CONFIG(debug, debug|release):libraryFiles.files = $$OUT_PWD/debug/*.a $$OUT_PWD/debug/*.prl
Release:libraryFiles.files = $$OUT_PWD/release/*.a $$OUT_PWD/release/*.prl
CONFIG(release, debug|release):libraryFiles.files = $$OUT_PWD/release/*.a $$OUT_PWD/release/*.prl
INSTALLS += libraryFiles
INSTALLS += libraryFiles
</code>
</syntaxhighlight>


You need to specify what files you want to copy with [http://doc.qt.io/qt-5/qmake-variable-reference.html#OUT_PWD $$OUT_PWD] and where you want to put them by using [http://doc.qt.io/qt-5/qmake-variable-reference.html#QT_INSTALL_HEADERS $$QT_INSTALL_HEADERS] and [http://doc.qt.io/qt-5/qmake-variable-reference.html#QT_INSTALL_LIBS $$QT_INSTALL_LIBS].
You need to specify what files you want to copy with [http://doc.qt.io/qt-5/qmake-variable-reference.html#OUT_PWD $$OUT_PWD] and where you want to put them by using [http://doc.qt.io/qt-5/qmake-variable-reference.html#QT_INSTALL_HEADERS $$QT_INSTALL_HEADERS] and [http://doc.qt.io/qt-5/qmake-variable-reference.html#QT_INSTALL_LIBS $$QT_INSTALL_LIBS].


For more information, see [http://doc.qt.io/qt-5/qmake-advanced-usage.html#installing-files Installing Files].


== Which approach to choose ==
==Which approach to choose==


Which approach to choose depends on your needs. When creating a shared library, you need to deploy it with your application. On the plus side, applications and libraries linked against a shared library are small. Whether to use QLibrary to load the .dll or just standard linking, depends on whether you have access to the headers and the .lib files, if you don't have access to those, then QLibrary is an alternative.
Which approach to choose depends on your needs. When creating a shared library, you need to deploy it with your application. On the plus side, applications and libraries linked against a shared library are small. Whether to use QLibrary to load the .dll or just standard linking, depends on whether you have access to the headers and the .lib files, if you don't have access to those, then QLibrary is an alternative.


Static linking results in a stand-alone executable. The advantage is that you will only have a few files to deploy. The disadvantage is that the executables are large. See the [http://doc.qt.io/qt-5/windows-deployment.html Deployment documentation] for more details on shared and static builds.
Static linking results in a stand-alone executable. The advantage is that you will only have a few files to deploy. The disadvantage is that the executables are large. See the [http://doc.qt.io/qt-5/windows-deployment.html Deployment documentation] for more details on shared and static builds.

Latest revision as of 18:23, 12 November 2021

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

Introduction

This tutorial illustrates different approaches for using a custom library in your application on Windows. The first part explains how to create a shared library and how to link against it in your application. The second part is about creating and using a static library.

To organize a bigger project with libraries and executables, take a look at SUBDIRS - handling dependencies

Creating a shared library

When creating a shared library that you would like to link against, then you need to ensure that the symbols that are going to be used outside the library are properly exported when the library is created. Subsequently imported when you are linking against the library. This can be done using Q_DECL_EXPORT and Q_DECL_IMPORT as shown in the following example:

test.h

#include <QWidget>

#if defined MAKE_TEST_LIB
    #define TEST_LIB_EXPORT Q_DECL_EXPORT
#else
    #define TEST_LIB_EXPORT Q_DECL_IMPORT
#endif
    
class TEST_LIB_EXPORT Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget *parent = nullptr);
};

test.cpp

#include "test.h"
#include <QtWidgets>

Widget::Widget(QWidget *parent) : QWidget(parent) {}

test.pro

TEMPLATE = lib
SOURCES += test.cpp
HEADERS += test.h
DEFINES += MAKE_TEST_LIB
QT += widgets

On Windows, MinGW will output .a and .dll, MSVC will output .lib and .dll.

On Linux, gcc/clang will output .so, .so.1, .so.1.0 and .so.1.0.0

.lib, .a and .so are import libraries. They are needed to link your code against the library.

See also the documentation on Creating Shared Libraries.

Linking your application against the shared library

In order to use the shared library in your application, you can include the headers of your library in your code and use the methods/classes from there. Also you need to link against the import library file (.lib, .a and .so). At runtime this loads the shared library (.so.1.0.0 / .dll) which has the implementation.

To set this up, you have to modify your application's .pro file. You need to inform qmake where to find the headers and the library. The INCLUDEPATH needs to point to the directory where the headers are installed, and the LIBS variable needs to point to the directory of the import library file. In addition you need to ensure that the shared library is found by either putting it in the application's directory or in the global PATH on windows and the LD_LIBRARY_PATH on linux.

For example:

loadTestLib.pro

TEMPLATE = app
TARGET =
DEPENDPATH += . ../testLib
INCLUDEPATH += ../testLib
LIBS += -L../testLib/debug -ltestLib
#Input
SOURCES += main.cpp

main.cpp

#include <QtWidgets>
#include "test.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.resize(100, 100);
    w.show();
    return a.exec();
}

alternatively you can right-click your project in Qt Creator and select "Add Library...", choose "External library" and browse for your library file:

  • For libraries compiled with MSCV compiler in windows, you look for .lib or .dll
  • On Windows, MinGW compiled linking libraries are in .a, but you will need to add it manually (as of Qt Creator 2.7). You could also try simply linking the .dll directly cause it would probably work. Don't try this with a MSVC compiled library .
  • On Linux you look for the .so file

This will append the following code to your *.pro file:

win32:CONFIG (release, debug|release): LIBS += -L$$PWD/build-MyLibrary/ -lmylibrary
else:win32:CONFIG (debug, debug|release): LIBS += -L$$PWD/build-MyLibrary/ -lmylibrary
else:unix: LIBS += -L$$PWD/build-MyLibrary/ -lMyLibrary

INCLUDEPATH += $$PWD/build-MyLibrary
DEPENDPATH += $$PWD/build-MyLibrary

$$PWD is used here to specify the full path leading to the directory containing your .pro file.

Note that for Unix/Linux systems the library file name is case sensitive, but for Windows you have to leave in all lower case.

Using QLibrary to load the shared library

QLibrary can be used for loading shared libraries at runtime. In this case you only need access to the .dll, access to the headers and .lib file(s) is not necessary.

The following example shows how to set up a library for usage with QLibrary. For the function names to be resolvable, they must be exported as C functions (i.e., without name mangling) from the library. This means that the functions must be wrapped in an extern "C" block if the library is compiled with a C++ compiler.

Since we are doing this on Windows we also must explicitly export the function from the DLL using Q_DECL_EXPORT and Q_DECL_IMPORT.

qlibraryLibrary.pro

TEMPLATE = lib
HEADERS += widget.h
SOURCES += widget.cpp
DEFINES += MAKE_TEST_LIB
QT += widgets

widget.h

#include <QWidget>

#if defined MAKE_TEST_LIB
 #define TEST_LIB_EXPORT Q_DECL_EXPORT
#else
 #define TEST_LIB_EXPORT Q_DECL_IMPORT
#endif

extern "C" TEST_LIB_EXPORT QWidget *createWidget1();

widget.cpp

#include <QtWidgets>
#include "widget.h"

QWidget *createWidget1()
{
    QWidget *widget = new QWidget();
    widget->resize(100, 100);
    return widget;
}

Loading the library using QLibrary

To load the library using QLibrary, you can simply pass in the .dll to the QLibrary constructor. Make sure the .dll is available in the application directory or in the global PATH. To use functions from the library in your application, you need to resolve them using QLibrary::resolve().

The example below loads the library created above and uses one of its functions to create and show a widget.

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QLibrary library("qlibraryLibrary.dll");
    if (!library.load())
        qDebug() << library.errorString();
    if (library.load())
        qDebug() << "library loaded";

    typedef QWidget *(*CreateWidgetFunction)();
    CreateWidgetFunction cwf = (CreateWidgetFunction)library.resolve("createWidget1");
    if (cwf) {
        QWidget *widget = cwf();
        if (widget) 
            widget->show();
    } else {
        qDebug() << "Could not show widget from the loaded library";
    }
    return app.exec();
}

Creating a static library

When creating a static library you need to specify the staticlib option to CONFIG in the .pro file. In contrast to the shared library example, you don't need to set up anything special for exporting and importing symbols in your .h file, since the library will be built into the application, for example:

test.pro

TEMPLATE = lib
CONFIG += staticlib
#Input
HEADERS += test.h
SOURCES += test.cpp

Using the static library in your application

Similar to what we did for the shared library loading, you need to set up the INCLUDEPATH to point to the directory where the headers are installed and the LIBS variable to point to the .lib file, for example:

useStaticLib.pro

TEMPLATE = app
TARGET =
CONFIG += console
QT += widgets
#Input
SOURCES += main.cpp
INCLUDEPATH += ../staticLibrary
LIBS += -L../staticLibrary/debug -lstaticLibrary

main.cpp

#include "test.h"
#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.resize(100, 100);
    w.show();
    return a.exec();
}

Installing a library

When you build your libraries, it could be useful to have one build for one framework and to centralize them : for example, you could having one library for Android, one for Windows and QT5.4 and one for Windows with Qt5.5 without having specific configurations. The easiest way is to put your files in the Qt folders by adding in your *.pro file :

headersDataFiles.path = $$[QT_INSTALL_HEADERS]/MyLib/
headersDataFiles.files = $$PWD/src/*.h
INSTALLS += headersDataFiles

libraryFiles.path = $$[QT_INSTALL_LIBS]
CONFIG(debug, debug|release):libraryFiles.files = $$OUT_PWD/debug/*.a $$OUT_PWD/debug/*.prl
CONFIG(release, debug|release):libraryFiles.files = $$OUT_PWD/release/*.a $$OUT_PWD/release/*.prl
INSTALLS += libraryFiles

You need to specify what files you want to copy with $$OUT_PWD and where you want to put them by using $$QT_INSTALL_HEADERS and $$QT_INSTALL_LIBS.

For more information, see Installing Files.

Which approach to choose

Which approach to choose depends on your needs. When creating a shared library, you need to deploy it with your application. On the plus side, applications and libraries linked against a shared library are small. Whether to use QLibrary to load the .dll or just standard linking, depends on whether you have access to the headers and the .lib files, if you don't have access to those, then QLibrary is an alternative.

Static linking results in a stand-alone executable. The advantage is that you will only have a few files to deploy. The disadvantage is that the executables are large. See the Deployment documentation for more details on shared and static builds.