In C language, global variables are defined in one .h file and used in multiple .cpp files.

general idea

First use the extern keyword to declare global variables in the .h file; then define global variables in one of the .cpp files; finally, you can use global variables in other .cpp files.

Verification steps

1. Create a new global.h file

#include <cstring>
#include <iostream>
using namespace std;
extern string tmp1;//声明全局变量tmp1 
extern string tmp2;

2. Create a new 1.cpp file

#include "global.h"
string tmp1;//定义全局变量tmp1 
string tmp2;
void getValue(){
	cout<<"1.cpp获取的全局变量值:tmp1="<< tmp1<<"  ,tmp2="<<tmp2<<endl;
}

3. Create a new 2.cpp file

#include "global.h"
void setValue(){
	cout<<"在2.cpp中输入tmp1和tmp2的值:"<<endl; 
	cout<<"tmp1:"; 
	cin>>tmp1;
	cout<<"tmp2:";
	cin>>tmp2;
}

4. Create a new main.cpp file

#include "1.cpp"
#include "2.cpp" 
int main(){
	setValue();//在2.cpp中对全局变量赋值 
	getValue();//在1.cpp中打印全局变量的值 
	return 0;
}

5. Screenshot of results

Guess you like

Origin blog.csdn.net/Olivia_2/article/details/117263035
Recommended