简体   繁体   中英

Inheritance from macros in Qt4

Part of my code looks something like this.

#include <QObject>
#define MYMACRO : public QObject
#define SIGNAL_MACRO Q_OBJECT signals: void testSignal(std::string s);
#define EMIT_MACRO emit testsignal(s);

class myclass MYMACRO
{
   SIGNAL_MACRO
...

void myclass::method()
{
   std::string s("string");
   EMIT_MACRO
}

If I write the contents of the macros to where they should be expanded it works fine. But if I keep the macros and let the preprocessor do the job then I get an 'undefined reference to myclass::testSignal(std::string)'. I don't understand what's the difference. The preprocessor should expand the macros as they are first encountered, exactly as if I'd written them out myself. I thought I could write anything in a macro and it will simply be copy-pasted to where it's needed.

I think the problem here might be that the Qt meta-object compiler is run before the C++ pre-processor, so it doesn't get to see the Q_OBJECT inside the SIGNAL_MACRO . From the Qt Reference Documentation :

The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.

My advice is, don't do it this way.

Are you sure that when you 'write the contents of the macros' manually, that you are writing code that is exactly the same as that produced by expansion of the macros?

It looks to me that the SIGNAL_MACRO declares the testSignal() function, but does not define it, ie function has no body, which would certainly result in the error you are seeing.

However, it is hard to tell from your code, because the use of macros is makes things confusing. I would kindly advise you not to use macros in this way, because it makes the code very hard to read and understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM