How to use precompiled headers in Qt project

spin_eight picture spin_eight · Dec 4, 2012 · Viewed 14.1k times · Source

My IDE: Visual Studio 2010, I use Qt add-in for VS, Qt ver. 4.8.1

I have faced with the problem while trying to create precompiled header(pch) in my Qt project.

My usuall approach for creating pch in non Qt project is:

  1. Create header;
  2. Include files which will be precompiled in header;
  3. For every source file in the project state in it`s properties if it will use pch;
  4. For one source file in project state creation of pch;
  5. Include pch in all source files.

As those action failed for Qt project I decided what it happens due to pch should be included to all files generated by MOC.

I read the article in QtAssistant on precompiled headers and did the following:

  1. Created header file;

  2. For all .cpp files in project set option use pch and for one create

  3. Converted to qmake generated project

  4. I ran qmake -project

  5. I modified generated .pro file, here it is:

    TEMPLATE = app TARGET = DEPENDPATH += . GeneratedFiles INCLUDEPATH += . PRECOMPILED_HEADER = StdAfx.h QT += network

    Input

    HEADERS += server.h StdAfx.h FORMS += server.ui SOURCES += main.cpp server.cpp StdAfx.h.cpp RESOURCES += server.qrc

  6. I ran qmake

  7. open .pro file and tried to build it and got the error:

    Error 2 error C1083: Cannot open include file: 'StdAfx.h': No such file or directory

What I am doing wrong?

Answer

Gordon Freeman picture Gordon Freeman · Dec 6, 2012

Create your precompiled header file and include the desired headers.

pch.hpp:

// precompiled headers

// add C includes here

#ifdef __cplusplus
// add C++ includes here

#include <iostream>
#include <QtGui>

#endif // __cplusplus

Then in your .pro file:

CONFIG += precompile_header
PRECOMPILED_HEADER = pch.hpp
HEADERS += pch.hpp

Qmake will now automatically set the correct options for the compiler.