对"TESTCLASS::TESTCLASS()"的未定义引用

Undefined reference to `TESTCLASS::TESTCLASS()'

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

尽管我阅读了一些关于该错误的谷歌结果,但我找不到此错误的问题,即使在尝试将所有内容简化为最基本的内容时也是如此。

那是我的测试类.h:

class TESTCLASS {
public:
TESTCLASS();
};
int x; // I added this for testing if the file is included from my main code file
x=10; // It is and throws this error: testclass.h:8:1: error: 'x' does not name a type, which I don't understand neither, but it't not the main problem here

测试类.cpp:

#include "testclass.h"
TESTCLASS::TESTCLASS() {
// do some stuff
}

这是我的主要代码文件:

#include "lib/testclass.h"
TESTCLASS test;
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}

这将引发错误

/var/folders/b5/qc8dstcn02v_hyvgxsq4w9vr0000gq/T//ccQOziAu.ltrans0.ltrans.o: In function `_GLOBAL__sub_I_test':
/Volumes/Daten/stefanherzog/Documents/Nextcloud/Programmierung/Arduino/200515_growboxLibrary_test/200515_growboxLibrary_test.ino:3: undefined reference to `TESTCLASS::TESTCLASS()'
collect2: error: ld returned 1 exit status
exit status 1

所以即使这是非常基本的,我也看不出问题所在!我在我的Arduino IDE(v1.8.12(中使用avr-g++编译器。

有人可以解释一下我做错了什么吗?

看起来你没有将testclass.cpp发送到你的编译器。如果是这样,你的问题不是来自你的代码,而是来自你的编译命令行。 使用 gcc,您应该具有类似以下内容:

g++ main.cpp lib/testclass.cpp -o testclass

我不知道arduino的编译过程,但我希望它能帮助您找到解决方案。

最简单的 put testclass.cpp 放入与 .ino 文件相同的文件夹中。它应该显示为一个单独的选项卡。

把testclass.h也放在那里。 并删除 lib 子文件夹。

并从 .h 文件中删除int x=10;定义。如果两个单元都包含testclass.h,则最终会出现重复错误。

顺便说一句:无论如何,函数外部的赋值x=10;都是无稽之谈。

在Arduino IDE中使用子目录时,子目录需要命名为utility。其实就是这样!

例如,具有此结构(在../Arduino/libraries/(:

./testclass
./testclass/testclass.h
./testclass/testclass.cpp
./testclass/sub
./testclass/sub/sub.h
./testclass/sub/sub.cpp

testclass.h:

#ifndef __TESTCLASS_H__
#define __TESTCLASS_H__
#include "utility/sub.h"
class TESTCLASS {
public:
TESTCLASS();
};
#endif

测试类.cpp:

#include "testclass.h"
TESTCLASS::TESTCLASS() {
// do some stuff
}

子H:

class SUBCLASS {
public:
SUBCLASS();
};

子.cpp:

#include "sub.h"
SUBCLASS::SUBCLASS() {
// do some stuff
}

你可以简单地在你的项目中包含"main"testclass.h,并实例化这个类,甚至是子类:

#include <testclass.h>
TESTCLASS test;
SUBCLASS sub;
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}