一、extern
函数的extern是默认设置
主要针对variable
extern int a;仅做声明不做定义 解决了在.h文件中定义全局变量导致的重定义问题
/*test.h*/
extern int a;
/*a.cpp*/
#include "test.h"
int a = 2;
/*b.cpp*/
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
cout<<a<<endl;
return 0;
}
/*makefile*/
main: a.cpp b.cpp
g++ a.cpp b.cpp -o main
./main 输出2 //注意 main函数只能定义一次
二、static
static int a; 同时完成declaration和definition
在不同的文件中引用,空间是重新分配的,这也就解决了重定义的问题
/*test.h*/
static int a = 2;
void fun();
/*a.cpp*/
#include "test.h"
#include <iostream>
using namespace std;
void fun()
{
a = 3;
cout<<a<<endl;
}
/*b.cpp*/
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
fun();
cout<<a<<endl;
return 0;
}
输出
3
2
Tips:
全局变量不能在函数外赋值