Using a third-party library with Qt is a simple process. Suppose you know of a cross-platform library that accepts audio samples of a cat's meows and translates them into English words. This library is named
CatWhisperer
, and has several files that it provides as part of its library. Your project,
MyQtApp
, stores these files in a folder named
3rdparty
:
要使用
CatWhisperer
library in
MyQtApp
,
qmake
requires the location and names of the
CatWhisperer
libraries. Optionally, you can also:
CatWhisperer
source code so that you don't have to type out the full path to each file when you include them in your own code.
MyQtApp
executable will be created.
The information above is provided in the
.pro
file, so that
qmake
can parse it and produce makefiles. Makefiles contain all the information needed by your compiler and linker to produce output, whether it is an executable, another library file, etc. The next sections explain the syntax with which
qmake
expects you to provide this information.
To be able to write
#include <CatWhisperer.h>
而不是
#include <3rdparty/CatWhisperer/include/CatWhisperer.h>
you can provide the path to the
CatWhisperer
包括
directory, using the
INCLUDEPATH
变量:
INCLUDEPATH += 3rdparty/CatWhisperer/include
To let
qmake
know where to find the
CatWhisperer
library files, use the
LIBS
变量:
LIBS += -L"3rdparty/CatWhisperer/lib" -lCatWhisperer
The first part of the expression lets the linker know in which directory it should look for the library files. The double quotes are only necessary when the path contains spaces, so we could have omitted them in this example.
The second part tells the linker which libraries to link against. We have two different library files for UNIX platforms and Windows, respectively:
libCatWhisperer.so
and
CatWhisperer.lib
. It is not necessary to specify the
.lib
extension, nor the
lib
prefix (on UNIX platforms).
默认情况下,
qmake
creates the executable in the same directory as the
.pro
file. We can choose our own directory using the
DESTDIR
变量:
DESTDIR = bin
That's it! You can now use the
CatWhisperer
library in your project. The final
.pro
file looks like this:
TARGET = MyQtApp TEMPLATE = app INCLUDEPATH += 3rdparty/CatWhisperer/include SOURCES += src/main.cpp LIBS += -L"3rdparty/CatWhisperer/lib" -lCatWhisperer
另请参阅 qmake 手册 and Qt Creator: Adding Libraries to Projects .