[CMake] Building a main.cpp containing a QObject subclass

Alexander Neundorf a.neundorf-work at gmx.net
Mon Oct 31 16:07:45 EDT 2011


On Monday 31 October 2011, Laszlo Papp wrote:
> Hi,
> 
> I would like to achieve something like this by using cmake:
> http://doc.qt.nokia.com/4.8/activeqt-comapp.html
> 
> I would like to have a QObject subclass in my main.cpp file since it
> has just one method for instance, and thus it would be a convenient
> approach for me.
> 
> This is my current CMakeLists.txt file:
> 
> [code]
> cmake_minimum_required(VERSION 2.8)
> 
> include_directories(${CMAKE_CURRENT_SOURCE_DIR}
> ${CMAKE_CURRENT_BINARY_DIR})
> 
> find_package(Qt4)
> 
> #set(CMAKE_AUTOMOC ON)
> 
> set(test_SRCS
>     main.cpp
> )
> 
> qt4_automoc(${test_SRCS})

I'd advice against using this.
Among others it only rechecks at cmake time, which is not enforced by simply 
editing the source files.

The straightforward way should be

qt4_wrap_cpp(mocFiles main.cpp)
add_executable(test ${test_SRCS} ${mocFiles})

and then _not_ include the moc file in main.cpp.


> add_executable(test ${test_SRCS})
> [/code]
> 
> This is my current main.cpp file:
> 
> [code]
> #include <QtCore/QObject>
> 
> class MyClass : public QObject
> {
>     Q_OBJECT
> }
> 
> #include "main.moc"
> 
> int main( int argc, char** argv )
> {
>     return 0;
> }
> [/code]


This should work with CMAKE_AUTOMOC ON.
I'll check why it doesn't.

Another options is to use automoc4, which is what is used by KDE4 (wrapped in 
KDE macros):
http://techbase.kde.org/Development/Tools/Automoc4
If you use master, its only dependency is QtCore, if you use the no-qt branch, 
it needs only C++ and a STL (this is what has been integrated in cmake).

Alex


More information about the CMake mailing list