Chinaunix首页 | 论坛 | 博客
  • 博客访问: 972427
  • 博文数量: 403
  • 博客积分: 27
  • 博客等级: 民兵
  • 技术积分: 165
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-25 22:20
文章分类

全部博文(403)

文章存档

2016年(3)

2015年(16)

2014年(163)

2013年(222)

分类: LINUX

2013-05-21 16:13:09

原文地址:内部连接和外部链接 作者:loughsky

今天看东西,不知道搞到内部链接这个概念上去了,于是翻了Stronstrup的TCPL,和c++编程思想,发现还是后者讲的不错。把英文的东西copy下来。

这个概念对写头文件是有帮助的。

Linkage

To understand the behavior of C and C++ programs, you need to know about linkage. In an executing program, an identifier is represented by storage in memory that holds a variable or a compiled function body. Linkage describes this storage as it is seen by the linker. There are two types of linkage: internal linkage and external linkage.

Internal linkage means that storage is created to represent the identifier only for the file being compiled. Other files may use the same identifier name with internal linkage, or for a global variable, and no conflicts will be found by the linker – separate storage is created for each identifier. Internal linkage is specified by the keyword static in C and C++.

External linkage means that a single piece of storage is created to represent the identifier for all files being compiled. The storage is created once, and the linker must resolve all other references to that storage. Global variables and function names have external linkage. These are accessed from other files by declaring them with the keyword extern. Variables defined outside all functions (with the exception of const in C++) and function definitions default to external linkage. You can specifically force them to have internal linkage using the static keyword. You can explicitly state that an identifier has external linkage by defining it with the extern keyword. Defining a variable or function with extern is not necessary in C, but it is sometimes necessary for const in C++.

Automatic (local) variables exist only temporarily, on the stack, while a function is being called. The linker doesn’t know about automatic variables, and so these have no linkage.

我归纳一下,const,static,typedef这些是指明内部链接的,把它放在头文件中,然后在多个元文件中包含之,则它们使用的是不同地址的。

而全局变量和函数名是指明外部链接的,把它放在头文件中,然后在多个元文件中包含之,则它们使用的是同一个地址的。

再看网上的一片文章,MISRA--作为工业标准的C编程规范

Rule 24. 在同一个编译单元中,同一个标识符不应该同事具有内部链接和外部链接的声名。

这里我略作说明:

我们通常将一些放在头文件里的变量声名为“外部链接”的,如:
extern UINT32 g_count; // 俗话叫变量声明(对应于变量定义,不分配实际空间)

对于“使用”这个变量的.c文件来说,这很好,因为g_count始终保持外部链接性质。可是对于定义g_count(实际分配空间)的.c文件来说,如果包含了上述的头文件,则在这个编译单元里就发生了内部链接和外部链接的冲突。解决办法是,定义g_count的文件尽量不要包含声名g_count的头文件。个人感觉这不是任何时候都做得到的,尤其是在对付遗留代码的时候。

Rule 25. 具有外部链接性质的标识符应该只声明一次。

阅读(825) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~