The Qt MOC and Preprocessor



  • Hi all!

    I understand that the MOC tool reads any class containing Q_OBJECT (as well as any other Qt extensions such as 'signals' and 'slots') and generates a separate source file containing the appropriate member function definitions.

    I also know that the MOC tool runs before the preprocessor.

    What I'm wondering is if after the MOC tool generates the definitions, the preprocessor goes in and expands the Q_OBJECT macro into the source file (in order to get the function prototypes), or does the MOC tool take care of expanding macros as well?

    I'm a bit confused on this point as I've heard that starting with Qt 5.0, the MOC is capable of macro expansion... Does the preprocessor still run after the MOC then?

    Thanks for your time!


  • Moderators

    Moc is a pre-compilation step. It is a separate tool, does not communicate with the compiler in any way and does not modify the files it processes. All its work results are placed in a separate file. Basically it just reads some code and generates more files for the compiler to compile.

    So the basic toolchain without moc is:
    compiler foo.h foo.cpp ->foo.obj
    linker foo.obj -> foo.exe
    and with moc it's
    moc foo.h -> moc_foo.cpp
    compiler foo.h foo.cpp -> foo.obj
    compiler foo.h moc_foo.cpp -> moc_foo.obj
    linker foo.obj moc_foo.obj -> foo.exe

    As for the "moc understands macros" part - it just means that it runs its own pre-processing pass to make sure macros are respected ie. something like this

    #if 0
       Q_OBJECT
    #endif
    

    will be understood and no code will be generated, where previously it would generate unconditionally. It has nothing to do with macro expansion the compiler does when it runs.

    Q_OBJECT is special only for moc. It understands what it is and generates members implementations in the moc_foo.cpp. For compiler Q_OBJECT is just a regular macro and is expanded as usual to crate the members declarations while processing foo.h.



  • @Chris-Kawa

    Thanks so much! I had a feeling it was like this, but just wasn't sure :) Thanks again!



  • @ConcordSpark https://woboq.com/blog/moc-myths.html gives some interesting details.


  • Moderators

    @Chris-Kawa
    Your post reads like poetry ;-)

    Eddy



  • @Eeli-K Thanks for that!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.