Qt5, CMake, AUTOMOC and precompiled headers

3.4k Views Asked by At

How to specify a precompiled header to the output of CMake (2.8.12.1) AUTOMOC ?

So far, in the CMakeLists.txt I've tried these two separately:

 set(AUTOMOC_MOC_OPTIONS "-bstdafx.h")
 set(AUTOMOC_MOC_OPTIONS "-fstdafx.h")

The generated AUTOMOC output when building the project (project_automoc.cpp) only contains the moc_xxx.cpp files:

/* This file is autogenerated, do not edit*/
/// <- stdafx.h should be here ?!?!
#include "moc_widget_fps.cpp"
#include "moc_widget_sysevents.cpp"
4

There are 4 best solutions below

3
On

AUTOMOC_MOC_OPTIONS doesn't affect the project_automoc.cpp file. It contains options passed to moc to create "moc_widget_fps.cpp" and "moc_widget_sysevents.cpp". Those should contain your pch includes.

0
On

A perhaps more elegant way is to disable precompiled headers for the mocs_... file. This allows you to keep AUTOMOC:

append_to_source_file_property(
  ${CMAKE_CURRENT_BINARY_DIR}/<PROJECT_NAME_HERE>_autogen/mocs_compilation.cpp
  COMPILE_FLAGS " /Y- ")

Alternatively if you can/are willing to change the name and contents of the precompiled header file, you can add this to it:

#ifdef HACK_FOR_TRICKING_MOC_INTO_INCLUDING_ME_IN_THE_MOCS_FILE_DO_NOT_DEFINE
Q_OBJECT
#endif

This will trick cmake into including it in the mocs_... file. You then need it to be at the top which requires a name change, files are sorted numbers first, then uppercase, then lowercase, so e.g. 1_precompiled.h should do the trick.

6
On

The correct variable to set is called CMAKE_AUTOMOC_MOC_OPTIONS. It is used to initialize the AUTOMOC_MOC_OPTIONS property of a target, i.e.:

set (CMAKE_AUTOMOC_MOC_OPTIONS "-bstdafx.h" "-fstdafx.h")

Also note that this will only make the Qt MOC compiler add the given includes to each generated moc_xxx.cpp file. The overall project_automoc.cpp will not be affected.

2
On

After some digging I decided to just turn the AUTOMOC feature off for projects that use precompiled headers:

set_target_properties (ProjectName PROPERTIES AUTOMOC FALSE)

# Set the headers that need moc'ing
file (GLOB MOC_FILES widget_filetransfer.h widget_main_menu.h widget_main_toolbar.h)
QT5_WRAP_CPP (MOC_SOURCES ${MOC_FILES})

...
# Force PCH for the generated MOC files
foreach (src_file ${MOC_SOURCES})
    set_source_files_properties (${src_file} 
  PROPERTIES COMPILE_FLAGS "/Yustdafx.h /FIstdafx.h"
)
endforeach()