具有链接的C++实体
2013-04-16 08:05
232 查看
具有链接的C++实体
分类: C++再学习系列 2009-07-11 17:13245人阅读 评论(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++链接数据库
- C++编译链接的那些小事 .
- c/c++使用VS2013连接MySQL与ubuntu下c链接mysql
- c++中数据表如何转成业务实体--map和结构体的相互转换
- C++动态链接/静态链接库编程
- 提供链接:《C++ Template Metaprogramming》第三章 第三章:深度探索元函数 中文翻译by刘未鹏
- C++学习推荐书单(附中英文电子书下载链接)
- vc6.0编译c++程序后在vc2008中调试的技巧(符号信息和链接)
- (转)const的内部链接属性(C++中适用)
- Linux链接库三(C跟C++之间动态库的相互调用)
- Cause: java.sql.SQLException: ORA-02018: 同名的数据库链接具有打开的连接
- C/C++/Fortran混合编程浅谈(一)直接链接方式
- C++常见编译/链接错误及其解决办法
- c++ opencv 下的动态链接库的创建和调用
- AutoSharedLibrary -- 基于模板元编程技术的跨平台C++动态链接载入库
- linux系统编译链接总结--高级c/c++编译技术读后总结(下)