具有链接的C++实体
2013-04-05 18:01
323 查看
具有链接的C++实体
分类: C++再学习系列 2009-07-11 17:13237人阅读 评论(0)
收藏
举报
c++编译器stringheaderfunctionfile
具有链接的实体,包括名字空间级的变量和函数,都是需要分配内存的。具有链接的实体如果在源文件(cpp)中出现多次,将意味着多次分配内存,每个内存空间定义一个特定的实体。这会导致:1) 空间膨胀;2) 出现多个变量,变量的状态不共享。
因此,不能将下面的代码放在头文件:
// avoid defining entities with external linkage in a header
int fudgeFactor;
std::string hello("Hello, world!");
void foo() {/* … */}
上述的全局变量和函数定义,在该头文件被多个源文件包含时,将导致连接错误,编译器将报告存在名字重复。
问题的解决方案:
//put just the declarations in the header:
extern int fudgeFactor;
extern string hello;
void foo(); //"extern" is optional with function declarations
//The actual definitions go in a single implementation file:
int fudgeFactor;
string hello("Hello, world!");
void foo() {/* … */ }
更应该注意的是static的头文件链接实体:
// avoid defining entities with static linkage in a header
static int fudgeFactor;
static string hello("Hello, world!");
static void foo() {/* … */ }
C++中,static数据和函数的重复是合法的。编译器将static对象解释成:每个文件都有一个私有副本(static的作用域是文件)。这意味着编译器不会报错,这样会导致每个文件都拥有自己的独立副本。故要慎用static变量。
相关文章推荐
- 具有链接的C++实体
- [C++再学习系列] 具有链接的C++实体
- [C++再学习系列] 具有链接的C++实体
- [C++再学习系列] 具有链接的C++实体
- C++ 类的静态成员详细讲解[静态成员变量链接错误]
- Linux链接库三(C跟C++之间动态库的相互调用)
- 把静态库链接进so库中及C++调用C
- 具有无损性连接和保持函数依赖的3NF分解C++实现
- 一个具有多值属性的实体怎么映射为关系
- Linux C/C++ 链接选项之静态库--whole-archive,--no-whole-archive和--start-group, --end-group
- C++链接器弱名称重复时链接的隐患
- c++中的信号与QML中的函数绑定(链接)起来 以及qml与c++交互重要笔记
- 在gridview中使具有特定值的链接不起作用
- 关于C++ vector<S>使用时,错误 5 error C2719: “_Val”: 具有 __declspec(align('16')) 的形参将不被对齐
- c++ 无法链接的外部变量
- 【C++】gcc/g++ 链接库的编译与链接
- C++编译链接
- c/c++ 链接、链接器
- 认识Lucene(4):使用Lucene、LingPipe做实体链接(Entity Linking)——数据预处理
- [C++]LeetCode: 124 Populating Next Right Pointers in Each Node II(链接二叉树)