Tx.Yang
Tx.Yang

Reputation: 11

Qt: How to manage QObject classes across dll and executable?

I have a Qt+cmake project in Win10. The project structure is

Class1 and Class2 are both child classes of QObject. MainWindow, as an executable, includes both Class1 and Class2. Class2 includes Class1. However, the compiler alerts:

mocs_compilation.cpp.obj:-1: error: LNK2019: unresolved external symbol "public: static struct QMetaObject const Class1::staticMetaObject" ...
Class2.cpp.obj:-1: error: LNK2001: unresolved external symbol "public: static struct QMetaObject const Class1::staticMetaObject" ...

I have done:

  1. Define Macro for exporting class from dll.
#if defined(DLL_DECL)
#define DLL_DECL_SPEC Q_DECL_EXPORT
#else
# define DLL_DECL_SPEC Q_DECL_IMPORT
#endif
  1. Class1 is defined in such a way.
class DLL_DECL_SPEC Class1: public QObject
{
    Q_OBJECT
    ...
}
  1. Class1 can be successfully instantiated in MainWindow.
  2. When Class2 includes Class1, the compilation always failed with the above errors.

I have tried:

  1. The other non-QObject classes can be successfully instantiated in both MainWindow and Class2.
  2. I have checked the target_link_libraries. Main links DLL1 and DLL2. DLL2 links DLL1.
  3. I tried declaring Class1 by only its name in header of Class2 and #include "Class1.h" in cpp of Class2. The error still remains...

Do you have any idea about these errors? In Qt, is one QObject class only allowed to be used once? Is there any way to work around?

Thanks for any suggestions!

Upvotes: 0

Views: 517

Answers (1)

Tx.Yang
Tx.Yang

Reputation: 11

As CristiFati mentioned, I create one ModuleXX.h for each dynamic library.

#if defined(DLL_DECLXX)
#define DLLXX_DECL_SPEC Q_DECL_EXPORT
#else
# define DLLXX_DECL_SPEC Q_DECL_IMPORT
#endif

In CMakeLists.txt, I rename the definitions as add_definitions(-DDLL_DECLXX). Now the include problem has been solved.

Upvotes: 1

Related Questions