作用域
C++
在全局作用域中声明的const变量是定义该对象文件的局部变量。
//var.c
extern const int MAX = 100; //必须用extern显式的声明const变量为全局变量
const int MAX_TEST = 100; //默认construction
//main.cpp
using namespace std;
extern const int MAX;
extern const int MAX_TEST;
void foo()
{
const int FOO = 255; //作用域为函数的局部变量
cout << "FOO=" << FOO << endl;
}
int main()
{
int x = MAX; //correct, 声明全局const变量,必须使用extern关键字做显示声明
cout << "x = " << x << endl;
int y = MAX_TEST; //compile error, 在全局作用域中声明的const对象,
//默认为文件的局部变量。NAX_TEST的作用域是var.cpp
extern const int FOO;
int z = FOO; //compile error, 非全局作用域声明的const对象,
//与非全局作用域声明的const对象的作用域一样
return 0;
}
$ g++ main.cpp var.cpp
/tmp/ccWHb099.o: In function `main':
main.cpp:(.text+0x76): undefined reference to `MAX_TEST'
main.cpp:(.text+0x7f): undefined reference to `FOO'
collect2: ld returned 1 exit status
C
在全局作用域中声明的const变量和非const变量的作用域都是一样的。
//var.c
const int MAX = 1024;
//main.c
#include <stdio.h>
extern int MAX;
int main()
{
printf("MAX=%d\n", MAX);
return 0;
}
$ gcc main.c var.c