Home >Backend Development >C++ >Why Am I Getting a \'Q_OBJECT Linking Error: \'undefined reference to vtable\'\' in My Qt Application?

Why Am I Getting a \'Q_OBJECT Linking Error: \'undefined reference to vtable\'\' in My Qt Application?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 03:51:02354browse

 Why Am I Getting a

Q_OBJECT Linking Error: 'undefined reference to vtable'

Consider the following Qt code snippet:

<code class="cpp">class T : public QObject, public QGraphicsItem
{
    Q_OBJECT

public:
    T() {}

    QRectF      boundingRect() const {return QRectF();}
    void        paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                      QWidget *widget) {}
};

int main()
{
    T t;
    return 0;
}</code>

When compiling this code, you may encounter linker errors like:

undefined reference to `vtable for T'
undefined reference to `vtable for T'
...

Solution:

This error typically occurs when the MOC-generated unit for your class is not included in the linking process. The MOC unit contains meta-information about the class, including its Q_OBJECT macro.

Possible Causes and Fixes:

  • Separate Header File: Ensure that your class declaration is in a separate header file. The build system may not be scanning implementation files to locate class declarations.
  • MOC Generation: Verify that the MOC unit has been generated. Run qmake again to force qmake to create the necessary MOC rules. If using Qt Creator, select "Run qmake" from the project context menu.
  • Q_OBJECT Macro: Confirm that you have properly used the Q_OBJECT macro in your class declaration. It should be placed before any constructor definitions.
  • Inheritance: If this class did not previously belong to the Qt meta-object system (e.g., it had no Q_OBJECT macro or inherited from another class), re-run qmake or make insignificant changes to your project file to trigger a qmake run.

The above is the detailed content of Why Am I Getting a \'Q_OBJECT Linking Error: \'undefined reference to vtable\'\' in My Qt Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn