C++中使用extern共享变量
Using extern in C++ to share vairables
我在网上查看了使用 extern 的例子,但是当我将它应用到我的项目时,它要么说该变量已在项目中多次定义,要么该变量超出范围
main.cpp
#include <SimPre.h>
void setup() {
example();
simController.println("Test");
}
void loop() {
example();
}
SimPre.h
#include <SoftwareSerial.h>
#ifndef SIM_PRE
#define SIM_PRE
extern SoftwareSerial simController(7, 8);
void example();
#endif
SimPre.cpp
#include <Arduino.h>
#include "SimPre.h"
void example() {
simController.println("Test");
}
上面的代码显示我试图从 main.c 访问 simController 变量,它也应该可以从 SimPre.c 访问,但是我得到一个错误:
libraries/SimPre/SimPre.cpp.o:(.bss.simController+0x0): multiple definition of `simController'
sketch/DilshadSIM.ino.cpp.o:(.bss.simController+0x0): first defined here
collect2: error: ld returned 1 exit status
在SimPre.h中声明为:
extern SoftwareSerial simController;
我在网上查看了使用 extern 的例子,但是当我将它应用到我的项目时,它要么说该变量已在项目中多次定义,要么该变量超出范围
main.cpp
#include <SimPre.h>
void setup() {
example();
simController.println("Test");
}
void loop() {
example();
}
SimPre.h
#include <SoftwareSerial.h>
#ifndef SIM_PRE
#define SIM_PRE
extern SoftwareSerial simController(7, 8);
void example();
#endif
SimPre.cpp
#include <Arduino.h>
#include "SimPre.h"
void example() {
simController.println("Test");
}
上面的代码显示我试图从 main.c 访问 simController 变量,它也应该可以从 SimPre.c 访问,但是我得到一个错误:
libraries/SimPre/SimPre.cpp.o:(.bss.simController+0x0): multiple definition of `simController'
sketch/DilshadSIM.ino.cpp.o:(.bss.simController+0x0): first defined here
collect2: error: ld returned 1 exit status
在SimPre.h中声明为:
extern SoftwareSerial simController;