Qt应用程序中未定义的引用错误

时间:2013-03-29 11:10:08

标签: c++ qt ld undefined-reference vtable

我有一个由CMake驱动的库和示例应用程序。所以,有一个类,我在库中使用:

sourceeditor.h

#ifndef SOURCEEDITOR_H
#define SOURCEEDITOR_H

#include <QWidget>
#include "novile_export.h"

namespace Novile
{

class SourceEditorPrivate;
class NOVILE_EXPORT SourceEditor : public QWidget
{
    Q_OBJECT
public:
    explicit SourceEditor(QWidget *parent = 0);
    ~SourceEditor();

private:
    SourceEditorPrivate * const d;

};

} // namespace Novile

#endif // SOURCEEDITOR_H

sourceeditor.cpp

#include <QtCore>
#include <QVBoxLayout>
#include <QWebView>
#include "novile_debug.h"
#include "sourceeditor.h"

namespace Novile
{

class SourceEditorPrivate
{
public:
    SourceEditorPrivate(SourceEditor *p = 0) :
        parent(p),
        aceView(new QWebView(p)),
        layout(new QVBoxLayout(p))
    {
        parent->setLayout(layout);
        layout->addWidget(aceView);
    }

    ~SourceEditorPrivate()
    {
    }

    void loadAceView()
    {
        aceView->load(QUrl("qrc:/ace.html"));
    }

private:
    SourceEditor *parent;
    QWebView *aceView;
    QVBoxLayout *layout;
};

SourceEditor::SourceEditor(QWidget *parent) :
    QWidget(parent),
    d(new SourceEditorPrivate(this))
{
    mDebug() << "Source Editor has been started";

    d->loadAceView();
}

SourceEditor::~SourceEditor()
{
}

} // namespace Novile

和示例:

的main.cpp

#include <QApplication>
#include "../src/sourceeditor.cpp"

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

    Novile::SourceEditor editor;
    editor.setGeometry(100, 50, 600, 300);
    editor.show();

    return app.exec();
}

然后我收到了很多ld错误:

CMakeFiles/example.dir/main.cpp.o: In function `Novile::SourceEditor::SourceEditor(QWidget*)':
../src/sourceeditor.cpp:39: undefined reference to `vtable for Novile::SourceEditor'
../src/sourceeditor.cpp:39: undefined reference to `vtable for Novile::SourceEditor'
CMakeFiles/example.dir/main.cpp.o: In function `Novile::SourceEditor::~SourceEditor()':
../src/sourceeditor.cpp:46: undefined reference to `vtable for Novile::SourceEditor'
../src/sourceeditor.cpp:46: undefined reference to `vtable for Novile::SourceEditor'
collect2: error: ld returned 1 exit status

此文件(main.cpp)代表示例应用程序,它应该测试库的核心功能。

1 个答案:

答案 0 :(得分:1)

问题很可能是因为您#include .cpp个文件:

#include "../src/sourceeditor.cpp"

你不应该这样做,而你不需要它。只需添加相应的标头sourceeditor.h,如果需要,还可以包含novile_debug.h标头。

然后,确保main.cppsourceeditor.cpp都是项目的一部分,这样编译器将处理这两个转换单元,链接器最终会将相应的对象代码合并到您的可执行文件中程序