7.1.  Building and Reusing Libraries

[ fromfile: reusinglibs.xml id: reusinglibs ]

Many of our examples link with various libraries that we have supplied. You can download the tarball src.tar.gz containing the code and libraries we use from our dist directory. Unpack the tarball and create a shell/environment variable CPPLIBS that contains the absolute path to the src/libs directory.

[Note] Note

When we set up projects that reuse these libraries, we always assume that the shell/environment variable CPPLIBS (or %CPPLIBS% in Windows) has been properly set to contain the "libs root".

This variable is used for two purposes: It is the parent directory of all the C++ source code for libraries supplied by us (or by you), and it is also the destination directory of the compiled shared object code for those libraries.

qmake can access an environment variable such as CPPLIBS from inside a project file using the syntax $$(CPPLIBS). qmake can also include other project file (fragments). For example, the project file in Example 7.1 includes the file common.pri, for the common application build settings you saw earlier in Example 1.6.

Example 7.1. src/xml/domwalker/domwalker.pro

# include common qmake settings
include (../../common.pri)

# this project depends on libdataobjects:
LIBS += -ldataobjects

# this directory contains the libraries:
LIBS += -L$$(CPPLIBS)

# Search here for headers:
INCLUDEPATH += . $$(CPPLIBS)/dataobjects

QT += xml gui

CONFIG += console
TEMPLATE = app

SOURCES += main.cpp slacker.cpp domwalker.cpp xmltreemodel.cpp
HEADERS += slacker.h domwalker.h xmltreemodel.h

In addition, the project adds some values to the LIBS and INCLUDEPATH qmake variables so the project can find dependent libraries and headers.

The command

qmake -project

overwrites the project file, and generates one that contains information based only on the contents of the current working directory. In particular, qmake cannot know about external libraries that you may need to build your project. If a project depends on an external library, the project file contains customizations to variables such as INCLUDEPATH and LIBS. Rerunning qmake -project clobbers those customizations, so don't.

For example, suppose you develop an application that uses our dataobjects library. The header files are in $CPPLIBS/dataobjects and the lib shared object files are in $CPPLIBS. Then you must add the following lines to the project file.

INCLUDEPATH += $$(CPPLIBS)/dataobjects  # the source header files
LIBS += -L$$(CPPLIBS)             # add this to the lib search path
LIBS += -ldataobjects                   # link with libdataobjects.so

Assignments to the LIBS variable generally contain two kinds of linker switches that are passed directly to the compiler and the linker. For more information about what the linker switches mean, see Section C.3