[CMake] Preventing multiple definitions of metaObject methods

Stephen Morris s-morris at n-eos.com
Fri Sep 13 11:25:55 EDT 2019


Suppose I have a class that derives from QObject, and contains the Q_OBJECT macro in its header file. When I compile it using AUTOMOC enabled, a "moc_myClass.cpp" file is created; if I manually include that file at the end of my 'myClass.cpp" file, then the moc file will be compiled there, otherwise CMake will take matters into its own hands and compile it anyway.

Now suppose make my class into a static library. The static library now contains the object code generated when moc_myClass.cpp was compiled.

I now include my static library from an application. Unless I enable AUTOMOC again, then I get a compilation error when Q_OBJECT is encountered. If I do enable it, then CMake generates a new moc_myClass.cpp file and, since it can't see the place where it was included in myClass.cpp, it goes ahead and recompiles it, placing the object code alongside the application's other object code.

Now, when the application links in the static library, it finds two definitions of moc_myClass.cpp's object code, and gives a multiple definition error.

All the ways I've come up with so far to work around this are so hacky that I'm embarrassed to mention them. There must be a proper way to handle this situation. Please can someone advise me what it is?

(N.B. I've been doing this for years with dynamic libraries are never encountered a problem, presumably because there the application doesn't get to see the inner workings of the library's object code. This issue does seem to be specific to static libraries, of which I have little prior experience).




More information about the CMake mailing list