static修饰的变量是不是仅限于本文件使用的问题C++

static修饰的变量是不是仅限于本文件使用的问题:

  1. 加了static确实限制了其作用域为本文件,在不include的情况下,即使Extern之后也不能使用(编译不过)
    例子如下:
    a.cpp文件如下:
#include<iostream>
using namespace std;
int a = 123;

b.cpp文件如下:

#include<iostream>
using namespace std;
extern int a;
int main(){
    
    
    cout<<"a is "<<a<<endl;
}

编译:

g++ a.cpp b.cpp -o target
./target

运行结果为:
a is 123。

如果修改a.cpp为:

#include<iostream>
using namespace std;
static int a = 123;

则编译会报错:
在函数‘main’中:
b.cpp:(.text+0xb):对‘a’未定义的引用
collect2: 错误:ld 返回 1
2. 如果include了,应该相当于预处理时直接展开了,无论加还是不加static,都是一样的可以使用。(用例略)

猜你喜欢

转载自blog.csdn.net/weixin_43919570/article/details/112986108