未定义的类引用

Undefined referance to class

本文关键字:引用 未定义      更新时间:2023-10-16

我知道这个问题已经被问了几千次了,但我被难住了。在过去的三天里,我一直在四处寻找,但没有结果。我一直犯这个错误,我不明白为什么。我只添加了我输入的/重要的代码。如果我注释掉我的代码,程序编译起来就没有问题。我做错了什么???

CMakeFiles/brewtarget.dir/MainWindow.cpp.o:在函数MainWindow::MainWindow(QWidget*)'中:MainWindow.cpp:(.text+0xb145):未定义对yeastCellCounter::yeastCellCounter()'的引用

CODE

mainwindow.cpp

#include "yeastcellcounter.h"
// a whole lot of stuff between these...
yeastCountDialog = new yeastCellCounter();

主窗口.h

class yeastCellCounter;
// A whole log of stuff between these...
yeastCellCounter *yeastCountDialog;

酵母计数器.cpp

#include "yeastcellcounter.h"
yeastCellCounter::yeastCellCounter(){}

yeastcellcounter.h

#ifndef YEASTCELLCOUNTER_H
#define YEASTCELLCOUNTER_H
class yeastCellCounter
{
public:
    yeastCellCounter();
};
#endif // YEASTCELLCOUNTER_H

这是cmakelist.txt 中的INCLUDE_DIRECTORIES指令

SET(ROOTDIR "${CMAKE_CURRENT_SOURCE_DIR}")
SET(SRCDIR "${ROOTDIR}/src")
SET(UIDIR "${ROOTDIR}/ui")
SET(DATADIR "${ROOTDIR}/data")
SET(TRANSLATIONSDIR "${ROOTDIR}/translations")
SET(WINDIR "${ROOTDIR}/win")
INCLUDE_DIRECTORIES(${SRCDIR})
INCLUDE_DIRECTORIES("${CMAKE_BINARY_DIR}/src") # In case of out-of-source build.
INCLUDE_DIRECTORIES("${CMAKE_BINARY_DIR}/QtDesignerPlugins")

每当您看到类型为undefined reference to ...的错误时,都是链接器错误。这意味着编译器已经完成了它的工作,并且所有的对象文件都已被编译而没有错误。现在是链接器将所有部分放在一个文件中的时候了。

在您的具体示例中,它表示找不到函数yeastCellCounter::yeastCellCounter()的定义。根据粘贴的代码,这个函数虽然是空的,但在文件yeascellcounter.cpp中有明确的定义。

您的cmakelists.txt文件似乎不完整。您尚未指定需要将哪些源文件链接在一起才能创建最终可执行文件。为此,您需要使用add_executable语句。

这里有一个简单的例子

问题是:

yeastCountDialog = new yeastCellCounter();

应该是:

yeastCountDialog = new yeastCellCounter;

(注意没有括号)。调用默认构造函数时总是不带括号。此外,您还需要将"yeastcellcounter.cpp"添加到cmake源列表中。