const全局变量自带内部链接属性(internal linka
2019-06-01 本文已影响0人
RC_HT
const全局变量自带内部链接属性(internal linkage)
之前一直以为全局变量都是一样的,那就是自动暴露出自己的链接符号,别的地方要用只要声明一下(extern)就可以了,但最近在一个项目中写代码的时候发现编译的时候总是报错,提示某个const全局变量符号未定义(undefined symbol)。代码示意(没有在func.h中声明,而是直接在另一个编译单元直接声明再使用):
//func.cpp
const int VAR = 0;
后来查看c++ primer才发现原来是因为const全局变量自带内部链接属性,也就是说上面的代码其实等价于:
//func.cpp
static const int VAR = 0;
标准写法
要对外暴露该链接符号就必须加上extern属性(在头文件中或者cpp中加都可以)。平时会忽略这个问题就是因为一般都会在头文件中加上extern的声明,而碰巧这一次我并没有在h中添加声明,所以造成符号未定义问题。
标准写法:
To define a single instance of a const variable, we use the keyword extern on both its definition and declaration(s):
也就是说在声明和定义处最好都加上extern:
//func.h
extern const int VAR;
//func.cpp
extern const int VAR = 0;