1. extern
微软官方的的介绍:
extern (C++) | Microsoft Learn
从介绍中可以看出,我们我们需要在使用到这个全局变量或函数的源文件中加入extern声明的变量或函数;这里是声明而不是重新定义,定义只需要一次。
2.用法示例(类)
参考:C++中extern用于类_c++ extern 类_圣骐的博客-CSDN博客
因为我把extern A aa; 这条命令放进了头文件,所以引用了该头文件的cpp源文件都执行了该条指令,但我觉得还是最好按上述参考资料中的写法比较好理解,不容易混淆,就是在哪里需要使用该全局对象,就在那里增加extern ....语句。
a.h
/*a.h*/
class A
{
public:
A();
~A();
void setA(int _a);
void setB(int _b);
int getA();
int getB();
private:
int a;
int b;
};
extern A aa;
a.cpp
/* a.cpp */
#include "../include/a.h"
#include <iostream>
A::A() {}
A::~A() {}
A aa;
void A::setA(int _a) {
a = _a;
}
void A::setB(int _b) {
}
int A::getA() {
return a;
}
int A::getB() {
return b;
}
b.h
/* b.h */
#pragma once
#include "a.h"
class B
{
public:
B();
~B();
int getA();
void setA(int a1);
private:
int a;
};
b.cpp
#include "../include/b.h"
#include <iostream>
B::B() {}
B::~B() {}
void B::setA(int a1)
{
a = a1;
aa.setA(a1);
}
int B::getA()
{
return a;
}
main.cpp
/* main.cpp */
#include <iostream>
#include "../include/b.h"
using namespace std;
int main()
{
B b;
b.setA(8);
cout << aa.getA() << endl;
return 0;
}
3.用法示例(变量)
上面是对全局对象的extern的用法,这里再运行一个结构体变量的extern用法
a.h
/*a.h*/
#pragma once
#include <string>
using namespace std;
struct student {
string name;
int age;
int score;
};
void get_stu(student stu);
a.cpp
/* a.cpp */
#include "../include/a.h"
#include <iostream>
struct student stu1 = { "tom", 18,90 };
void get_stu(student stu)
{
std::cout << stu.name << endl;
std::cout << stu.age << endl;
std::cout << stu.score << endl;
}
b.h
/*b.h*/
#pragma once
#include "../include/a.h"
void set_stu();
b.cpp
/*b.cpp*/
#include "../include/b.h"
#include <iostream>
extern student stu1;
void set_stu()
{
stu1.name = "lilei";
stu1.age = 20;
stu1.score = 60;
}
main.cpp
/*main.cpp*/
#include <iostream>
#include "../include/b.h"
using namespace std;
extern student stu1;
int main()
{
get_stu(stu1);
set_stu();
get_stu(stu1);
return 0;
}
编译并运行结构如下: