Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-28 03:51:02
Original
240 people have browsed it

 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>
Copy after login

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

undefined reference to `vtable for T'
undefined reference to `vtable for T'
...
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!