Qt toolkit - Using the Meta Object Compiler

# Using the Meta Object Compiler

The Meta Object Compiler, moc among friends, is the program which handles the C++ extensions in Qt.

The moc reads a class declaration and produces a C++ source file containing the names of all signals and slots for that class (and a little more). This C++ source file the moc outputs must be compiled and linked with the implementation of the class (or it can be #included into the source file).

Using the moc is introduced in chapter 7 of the Qt Tutorial. Chapter 7 includes a simple Makefile that uses the moc and of course source code that uses signals and slots.

## Invoking moc

Here are the command-line options supported by the moc:

-o file
  Write output to file rather than to stdout.
-f
  Force the generation of an #include statement in the output. This is the default for files whose name matches the regular expression \.[hH][^.]* (ie. the extension starts with H or h). This option is only useful if you have header files that do not follow the standard naming conventions.
-i
  Do not generate an #include statement in the output. This may be used to run the moc on on a C++ file containing one or more class declarations. You should then #include the meta object code in the .cpp file. If both -i and -f are present, the last one wins.
-nw
  Do not generate any warnings. Discouraged.
-ldbg
  Write a flood of lex debug information on stdout.
-dbg
  Treat all non-signal members as slots, for internal debugging purposes. This is not useful for programming Qt clients.
-p path
  Makes the moc prepend path/ to the file name in the generated #include statement (if one is generated).
-q path
  Makes the moc prepend path/ to the file name of qt #include files in the generated code.

## Usage

moc is almost always invoked by make(1), not by hand.

moc is typically used with an input file containing class declarations like this skeleton:

        class YourClass : public QObject {
            Q_OBJECT
        public:
            YourClass( QObject * parent=0,
                                  const char * name=0 );
            ~YourClass();

        signals:

        public slots:

        };

Here is a useful makefile rule if you only use GNU make:

        m%.cpp: %.h
                moc $< -o $@

If you want to write portably, you can use individual rules of the following form:

        mNAME.cpp: NAME.h
                moc $< -o $@

You must also remember to add mNAME.cpp to your SOURCES (substitute your favorite name) variable and mNAME.o to your OBJECTS variable.

(While we prefer to name our C++ source files .cpp, the moc doesn't know that, so you can use .C, .cc, .CC, .cxx or even .c++ if you prefer.)

If you have class declarations in C++ files, we recommend that you use a makefile rule like this:

        NAME.o: mNAME.cpp

        mNAME.cpp: NAME.cpp
                moc -i $< -o $@

This guarantees that make(1) will run the moc before it compiles NAME.cpp. You can then put

        #include "nNAME.cpp"

at the end of NAME.cpp, where all the classes declared in that file are fully known.

## Diagnostics

Sometimes you may get linkage errors, saying that YourClass::className() is undefined or that YourClass lacks a vtbl. Those errors happen most often when you forget to compile the moc-generated C++ code or include that object file in the link command.

The moc will warn you about a number of dangerous or illegal constructs.

## Bugs

The moc does not expand #include or #define, it simply skips any preprocessor directives it encounters. This is regrettable, but is normally not a problem in practice.

The moc does not handle all of C++. The main problem is that class templates cannot have signals or slots. This is an important bug. Here is an example:

        class SomeTemplate<int> : public QFrame {
            Q_OBJECT
        [...]
        signals:
            void bugInMocDetected( int );
        };

Less importantly, the following constructs are illegal. All of them have workarounds which we think are better alternatives, so fixing these bugs is not a high priority for us.

### Multiple inheritance requires QObject to be first

If you are using multiple inheritance, moc assumes that the first inherited class is a subclass of QObject. Also, be sure that only the first inherited class is a QObject.

        class SomeClass : public QObject, public OtherClass {
        [...]
        };

This bug is almost impossible to fix; since the moc does not expand #include or #define, it cannot find out which one of the base classes is a QObject.

### Function pointers can not be arguments to signals or slots

In most cases where you would consider that, we think inheritance is a better alternative. Here is an example of illegal syntax:

        class someClass : public QObject {
            Q_OBJECT
        [...]
        public slots:
            void apply(void (*applyFunction)(QList*, void*), char*);
        };

You can work around this restriction like this:

        typedef void (*ApplyFunctionType)(QList*, void*);

        class someClass : public QObject {
            Q_OBJECT
        [...]
        public slots:
            void apply( ApplyFunctionType, char *);
        };

(It may sometimes be even better to replace the function pointer with inheritance and virtual functions, signals or slots.)

### Friend declarations can not be placed in signals or slots sections

Sometimes it will work, but in general, friend declarations can not be placed in signals or slots sections. Put them in the good old private, protected or public sections instead. Here is an example of the illegal syntax:

        class someClass : public QObject {
            Q_OBJECT
        [...]
        signals:
            friend class ClassTemplate<char>;
        };

### Signals and slots cannot be upgraded

The C++ feature of upgrading an inherited member function to public status is not extended to cover signals and slots. Here is an illegal example:

        class Whatever : public QButtonGroup {
        [...]
        public slots:
            void QButtonGroup::buttonPressed;
        [...]
        };

The QButtonGroup::buttonPressed() slot is protected.

C++ quiz: What happens if you try to upgrade a protected member function which is overloaded?

1. All the functions are overloaded.
2. That is not legal C++.

### Type macros can not be used for signal and slot arguments

Since the moc does not expand #define, type macros that take an argument will not work in signals and slots. Here is an illegal example:

        #ifdef ultrix
        #define SIGNEDNESS(a) unsigned a
        #else
        #define SIGNEDNESS(a) a
        #endif

        class Whatever : public QObject {
        [...]
        signals:
            void someSignal( SIGNEDNESS(a) );
        [...]
        };

A #define without arguments works.

### Nested classes cannot be in the signals or slots sections nor have signals or slots

Here's an example:

        class A {
            Q_OBJECT
        public:
            class B {
            public slots:
                void b();       // Nested class with slot
            [....]
            };
        signals:
            class B {
                void b();       // Nested class in signals:

            [....]
            }:
        };

### Constructors can not be used in signals or slots sections

It is a mystery to me why anyone would put a constructor on either the signals or slots sections. You can not, anyway (except that it happens to work in some cases). Put them in private, protected or public sections, where they belong. Here is an example of the illegal syntax:

        class SomeClass : public QObject {
            Q_OBJECT
        public slots:
            SomeClass( QObject *parent, const char *name )
                : QObject( parent, name ) {}
        [...]
        };

### Signals and slots may not have default arguments

Since signal->slot binding occurs at run-time, it is conceptually difficult to use default parameters, which are a compile-time phenomenon. This will fail:

        class SomeClass : public QObject {
            Q_OBJECT
        public slots:
            void someSlot(int x=100);
        };

### Signals and slots may not have template arguments

Declaring signals and slots with template-type parameters will not work as expected, even though the moc will accept it. Connecting the signal to the slot in the following example, the slot will not get executed when the signal is emitted:

       [...]
       public slots:
           void MyWidget::setLocation (pair<int,int> location);

       [...]
       public signals:
           void MyObject::moved (pair<int,int> location);

However, you can work around this limitation by explicitly typedef'ing the parameter types, like this:

       typedef pair<int,int> IntPair;
       [...]
       public slots:
           void MyWidget::setLocation (IntPair location);

       [...]
       public signals:
           void MyObject::moved (IntPair location);

This will work as expected.