Cpp Primer杂记–extern const的声明注意
2016-07-21 23:47
357 查看
Cpp Primer杂记–extern const的声明注意
结论:在用extern const 时,在.h文件中对const 的 object 进行的一些非声明操作在链接时会认为是定义而可编译而无法链接(重定义).
解释:
错误代码:
这里多出file_2.h 嵌套在file_1.h中再include到main里,那么如果在file_2.h对bufSize进行了一些非声明操作会导致其的重定义.vs2015_Pro 出现:fatal error LNK1169.
或者file_2.h改为
正确代码:
将定义一定写到.cpp中
结论:在用extern const 时,在.h文件中对const 的 object 进行的一些非声明操作在链接时会认为是定义而可编译而无法链接(重定义).
解释:
错误代码:
这里多出file_2.h 嵌套在file_1.h中再include到main里,那么如果在file_2.h对bufSize进行了一些非声明操作会导致其的重定义.vs2015_Pro 出现:fatal error LNK1169.
//file_1.h #include "file_2.h" extern const int bufSize; //file_2.h extern const int bufSize = 5; //main.c #include "file_1.h" int main() { }
或者file_2.h改为
//file_2.h int get_bufSize(void) { return bufSize; }
正确代码:
将定义一定写到.cpp中
#include "file_2.h" extern const int bufSize; //file_2.h extern const int bufSize; //file_2.cpp extern const int bufSize = 5; //main.c #include "file_1.h" int main() { }
相关文章推荐
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- Deploying Control Plane Policing
- Thrift的required和optional源码分析
- c++中extern关键字详解 知识补充笔记
- MBProgressHUD的基本使用
- 意外的结果-C++中的移位操作
- MFC自定义类访问主窗口控件
- LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main 问题解决
- 单向链表LinkedList的使用
- cpp函数返回对象&&数组
- 继承、组合、委托
- vim配置
- LIB和DLL的区别与使用
- Learn note(cpp): take care when use new in a code block.
- 如果在主串Tag的第pos个位置后存在
- BF算法
- 一个悲伤的gcc故事
- 用gcc编译opencv程序出错
- cocos2d-x-3.2创建项目中出现的一些问题