之前学习c语言的时候,要用到全局的常量,必须要在.h文件中用static const 定义。
例如:
global.h
#include <stdio.h>
static const int a = 5;
static const float b = 5;
extern int c;
void test();
test.c
#include "global.h"
int c = 7;
void test() {
printf("a = %d\n", a);
printf("b = %f\n", b);
c = 6;
}
main.c
#include "global.h"
int main() {
test();
printf("a = %d\n", a);
printf("b = %f\n", b);
printf("c = %d\n", c);
return 0;
}
然后,转到c++以后,自然而然的保留了这个习惯。直到今天,在一个项目中发现全局常量居然没用static修饰,链接时也没问题,才直到,在c++中,是不用static 修饰全局常量也没问题的。只是,全局的常量,一定要用const限定。