1.static。
不同的cpp文件中可以定义同名的static变量。如:static int kk = 3;
这样不会造成重定义的问题,因为static作用范围是单个编译单元。每个编译单元会开辟独立的空间来存储kk变量。并且无法用extern在其它cpp文件中使用。
2.extern
extern与static不能一起使用,其作用范围是工程的全局范围。如果在多个cpp中重复定义了同名extern变量,就会出现重定义问题。比如:int kk = 3,extern int kk = 3。
3.const
const单独使用或者与static一起使用的时候其作用范围与static相同,即不同的cpp文件中可以定义同名的const变量。
它和extern一起使用时,作用范围和extern一样。
声明:extern const char g_szBuffer[];
定义:const char g_szBuffer[] = “123456”;
定义只能定义一次。
#ff.h
extern const char g_szBuffer[];
#tt.cpp
#include"ff.h"
const char g_szBuffer[] = "123456";
#main.cpp
#include<iostream>
#include"ff.h"
int main() {
std::cout << g_szBuffer;
return 0;
}
4.extern和static
//kk.cpp
int kk = 5;
//main.cpp
extern int kk;
static int kk=3;
cout<<kk<<endl;
输出3。
5.extern和const(kk.cpp相同)
//main.cpp
extern int kk;
const int kk=3;
cout<<kk<<endl;
编译出错,声明与定义不符合。
6.(kk.cpp相同)
//main.cpp
const int kk=3;
cout<<kk<<endl;
输出3
7.(kk.cpp相同)
//main.cpp
static int kk=3;
cout<<kk<<endl;
输出3
8. extern和static const或const(kk.cpp相同)
//main.cpp
extern int kk;
static const int kk=3;
//const int kk=3;
cout<<kk<<endl;
编译出错,定义与声明不符。