const对象默认为文件的局部变量

在全局作用域里定义非const变量时,它在整个程序中都可以访问。可以把一个非const变量定义在一个文件中,假设已经做了合适的声明,就可以在另外的文件中使用这个变量:

//file_1.h

int counter;  //definition

//file_2.h

extern int counter;  //uses counter from file_1.h

++counter;    //increments counter defined int file_1.h

与其他变量不同,除非特别说明,在全局作用域声明的const变量是定义该对象的文件的局部变量。此变量只存在于那个文件中,不能被其他文件访问。

通过指定const变量为extern,就可以在整个程序中访问const对象。

//file_1.h

extern const int bufSize fcn();

//file_2.h

extern const int bufSize;    //uses bufSize from file_1.h

for(int index = 0; index != bufSize; ++index)

  //……

注意:非const变量默认为extern。要使const变量能够在其他文件中访问,必须显式地指定它为extern。

原文地址:https://www.cnblogs.com/BeyondTechnology/p/1837898.html