Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 标题中不允许全局变量?_C++_Arduino_Platformio - Fatal编程技术网

C++ 标题中不允许全局变量?

C++ 标题中不允许全局变量?,c++,arduino,platformio,C++,Arduino,Platformio,我正在尝试为我的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 colle

我正在尝试为我的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
对我来说,这个错误听起来像是如果你没有include-guard或使用pragma一次,你会得到的错误,但它们并没有解决我的问题

这是我的主页。cpp:

#include <Arduino.h>
#include "test.hpp"

void setup() {
  Serial.begin(115200);
  Serial.println(value);
}

void loop() {
}

test.cpp只包含test.hpp,不做其他任何事情。

您的项目中似乎有两个源文件:
main.cpp
test.cpp
。两者都可能包括test.hpp。因此,现在每个源文件都独立地拾取了一个
变量。因此链接器会感到困惑,因为它不知道每个模块应该使用哪个
值。而且您可能不需要这个全局变量的多个实例。你只要一个

在test.hpp中执行此操作:

extern int value;
然后在test.cpp中:

int value = 3;

项目中似乎有两个源文件:
main.cpp
test.cpp
。两者都可能包括test.hpp。因此,现在每个源文件都独立地拾取了一个
变量。因此链接器会感到困惑,因为它不知道每个模块应该使用哪个
值。而且您可能不需要这个全局变量的多个实例。你只要一个

在test.hpp中执行此操作:

extern int value;
然后在test.cpp中:

int value = 3;

边注:侧记:我已经有一段时间以来,我在纯C++中编程了一些更大的东西,但我想我从来没有遇到过问题。与ARDuiOS C++有什么不同吗?这种行为是从C继承的。几十年来一直没有改变。它不是C++编译器有问题,而是链接器。某些链接器可能具有命令行选项,如果它看到多个符号定义或仅给出警告,则可以“选择一个”。但是在实践中,你并不想在头文件中定义变量,只是声明它们。谢谢两个解释,自从我上次在C++编程了一些大的东西以来,已经有一段时间了,但是我想我从来没有遇到过问题。与ARDuiOS C++有什么不同吗?这种行为是从C继承的。几十年来一直没有改变。它不是C++编译器有问题,而是链接器。某些链接器可能具有命令行选项,如果它看到多个符号定义或仅给出警告,则可以“选择一个”。但实际上,您确实不想在头文件中定义变量,只需声明它们即可。感谢这两种解释