Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference to staticMetaObject

Tags:

c++

qt

It looks like Qt is not handling the Q_GADGET macro properly, because i am getting the error below. Anyone know why?

ERROR: undefined reference to `Exception::staticMetaObject'

EDIT: Later i found that the MOC doesn't generate moc_exception.cpp. Sometimes when i switch the compiler kit it compiles fine but than if i add another class that inherits Exception, it again doesn't work. The problem needs to be somewhere in MOC which ignores the Q_GADGET macro in some conditions?

I have Qt 5.5.0.

project.pro

CONFIG += c++11

QT += core
QT -= gui

SOURCES += \
    main.cpp

HEADERS += \
    nobject.h \
    exception.h

nobject.h

#ifndef NOBJECT_H
#define NOBJECT_H

#include <QObject>

class NObject
{

    Q_GADGET

public:
    NObject() {}
    virtual ~NObject() {}

};

#endif // NOBJECT_H

exception.h

#ifndef EXCEPTION_H
#define EXCEPTION_H

#include "nobject.h"

class Exception : public NObject
{

    Q_GADGET

public:
    Exception() {}
    virtual ~Exception() {}

};

#endif // EXCEPTION_H

main.cpp

#include <iostream>

#include "exception.h"

using namespace std;

int main(int argc, char* argv[]) {

    Exception nobject;

    std::cout << Exception::staticMetaObject.className() << std::endl;

    return 0;
}
like image 859
Krab Avatar asked Dec 08 '15 23:12

Krab


2 Answers

I suspect running qmake might solve your problem. Remember to re-run qmake every time you add or remove Q_GADGET or Q_OBJECT macro to get moc tool to re-generate code for meta data.

I didn't find any problem in your code by looking it so I copy-pasted the code to my machine and built and ran it. It built ok after I added implementation for NObject constructor. I built and ran it successfully on Qt5 and Qt4, and the program printed Exception on the console.

Qt 5:

> ~/temp/qgadgettest$ qmake --version
QMake version 3.0
Using Qt version 5.2.1 in /usr/lib/i386-linux-gnu

> /temp/qgadgettest$ ./qgadgettest 
Exception

Qt 4:

> ~/temp/qgadgettest$ qmake-qt4 --version
QMake version 2.01a
Using Qt version 4.8.6 in /usr/lib/i386-linux-gnu

> ~/temp/qgadgettest$ ./qgadgettest 
Exception
like image 168
talamaki Avatar answered Nov 08 '22 15:11

talamaki


In my environment, this code is correct. But I have added to the body of the constructor NObject.

like image 1
Alex Gurkin Avatar answered Nov 08 '22 15:11

Alex Gurkin