[CMake] Preventing multiple definitions of metaObject methods

Kyle Edwards kyle.edwards at kitware.com
Fri Sep 13 11:53:34 EDT 2019


On Fri, 2019-09-13 at 15:25 +0000, Stephen Morris wrote:
> 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).

Stephen,

Could you post a minimally reproducible example with CMakeLists.txt and
accompanying source code? I am currently working on a Qt-based project
with static libraries and have not encountered this issue.

Kyle


More information about the CMake mailing list