ulidtko ulidtko -4 years ago 133
C++ Question

What is the right way to include Qt headers?

So far I know several ways to

Qt classes:

  • #include <QtModule>

    This brings all classes of a specific module, for example
    and numerous others from
    #include <QtXml>

  • #include <QClassName>

    This adds declaration of a specific class one may want to use, e.g.

  • #include <qcstyleheader.h>

    This has effect of the previous method, except for differently looking header name.

So I wonder, are there any other ways to
Qt classes? Are they equivalent, or are some of them preferred to others because of some reasons? Does this depend on
-ing inside a
or a
file? Does this influence compilation speed and size of the executable?

In short, what is the best way to go?

Answer Source

As a rule, the more header files there are, the longer it takes the compiler to parse each module. (Obviously precompiled headers render some of this moot.) So you generally want to include the fewest header files necessary to build your app correctly.

If you are only using a few classes in a given compilation unit, then just include the classes by name, in the modern style:

#include <QEvent>
#include <QPainter>
#include <QFont>

If you use a large number of classes from a given module, it is probably just as easy to include the module-level header, such as:

#include <QtGui>

You generally only use the older .h style if a newer style header doesn't exist.

Now precompiled headers mitigate many of these issues by compiling once into a binary form. But there is still a cost to loading the precompiled symbols into memory and searching through them at compilation time. So the less you put in, the more efficient the build will be.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download