关于一个文件中的全局变量在其他文件中的使用

错误:多重定义 和 xxx变量已经在xxx.obj中定义

当在一个.cpp文件中定义了一个全局变量之后,需要在其他文件中使用时,需要用到关键字extern

当使用extern修饰一个变量时,例如extern int x;   代表当前变量x 的定义来自于其他文件,当进行编译时,会去其他文件里面找,

在当前文件仅做声明,而不是重新定义一个新的变量

main.cpp

#include <iostream>
#include "Some.h"
using namespace std;
 
extern int a;
int main() {
	Some * some = new Some;
	some->prntf();
	a= 50;
	cout << "main:" << a<< endl;;
	delete some;
	system("PAUSE");
	return 0;
}

Some.h

#pragma once
class Some
{
public:
	Some();
	~Some();
	void prntf();
};

Some.cpp

#include "Some.h"
#include <iostream>
using namespace std; 
int a;
 
Some::Some() {
	a= 20;
}
Some::~Some() {
 
}
 
void Some::prntf() {
	cout << "some:" << a<< endl;;
}

 当一个全局变量需要多文件中使用的时候,应当把这个变量的定义放在.cpp文件中而不是.h文件

转自:https://blog.csdn.net/qq_26559913/article/details/77892766

猜你喜欢

转载自blog.csdn.net/m0_37806112/article/details/82730578