在C++中使用extern来共享vairables

Using extern in C++ to share vairables

本文关键字:共享 vairables extern C++      更新时间:2023-10-16

我在网上看过使用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;