问题描述
我正在尝试为我的 PlatformIO Arduino 项目使用单独的文件,但出现此错误:
.pio/build/uno/src/test.cpp.o (symbol from plugin): In function `value':
(.text+0x0): multiple deFinition of `value'
.pio/build/uno/src/main.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
对我来说,这个错误听起来就像你没有包含守卫或使用 pragma 一次会得到的错误,但他们没有解决我的问题。
这是我的 main.cpp:
#include <Arduino.h>
#include "test.hpp"
void setup() {
Serial.begin(115200);
Serial.println(value);
}
void loop() {
}
test.hpp:
#ifndef TEST_HPP
#define TEST_HPP
int value = 3;
#endif
test.cpp 只包含 test.hpp,不执行其他任何操作。
解决方法
您的项目中似乎有两个源文件:main.cpp
和 test.cpp
。两者都可能包括 test.hpp。所以现在每个源文件都独立地选择了一个 value
变量。因此链接器会感到困惑,因为它不知道每个模块应该使用哪个 value
。而且您可能不想要这个全局变量的多个实例。你只想要一个。
改为在 test.hpp 中执行此操作:
extern int value;
然后在 test.cpp 中:
int value = 3;