You can tell CMake to enable moc support on the target by either:
set(CMAKE_AUTOMOC 1) # setting this variable
add_library(mylib) # before this call
# or by setting the property
set_property(TARGET mylib PROPERTY AUTOMOC 1)
# or by using the Qt API
qt5_wrap_cpp(moc_files swidgets.cpp TARGET mylib)
target_sources(mylib PRIVATE ${moc_files})
What is supposed to be defining your GLOBAL_EXPORTS symbol? It looks like your code is expecting that to be defined when building the export_dll library, but nothing seems to be.
Rather than providing your own hand-written Global.h, consider taking a look at CMake’s GenerateExportHeader module. The docs for that module are worth a read.
Nothing there is definingGLOBAL_EXPORTS. That code is only checking if it is defined. I also think you might have the sense of the block that checks it reversed. Compare your hand-written file with the one that GenerateExportHeader creates.
I have tried GenerateExportHeader , and it can solve my problem. But I still feel confuzed.
If the bug is caused by GLOBAL_EXPORTS, why I can correctly generate the dll if I remove Q_OBJECT? If I remove Q_OBJECT, I can correctly generate dll, and import the generated dll in other project.
Q_OBJECT expands to a whole bunch of stuff. It defines and calls methods, and adds some static members.
If you have your defines backwards, like you had, you’re not exporting the things correctly, and the linker cannot find the definitions.
If you remove the macro, no “special souse” will be added, so you won’t see the problem (at least not right away - it will eventually appear again).
As you extend your class, it’s almost guaranteed that at some point you’ll call some unexported method or something like that.
In any case this has already nothing to do with CMake and everything to do with C/C++, shared objects, and symbol visibility. If you want to know more, google something along those terms.