imjacob的专栏

首页博文目录订阅
正 文

内部链接和外部链接

(2006/12/27 19:40)

今天看东西,不知道搞到内部链接这个概念上去了,于是翻了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. 具有外部链接性质的标识符应该只声明一次。

评 论
2楼 imjacob 发表于 2009/5/30 18:11 回复
在《大规模c++程序设计》一书中对这个问题讲解的非常详细。另外《c++编程思想》好像也是,大家可以去看看
1楼 aly_boy(游客) 发表于 2008/8/10 12:06 回复
const 在c里是external linkage.在c++中是internal linkage.
博 主
进入imjacob的首页
博客名称:雅克的一府
日志总数:513
评论数量:853
访问次数:1885656
建立时间:2006/11/23 20:52
导 航
公 告
Locations of visitors to this page 本博客主要用于个人学习与资料收藏。当然大家应该读了之后也能学到不少东西。其中大多数资料都是来自网络,我转载时尽可能地表明文章出处与原作者姓名,但由于很多资料经多人转载,已不清楚原作者信息与出处,所以未表明相关…
评 论
链 接

ARM+LINUX 嵌入式博客
http://blog.chinaunix.net/u1/58780/index.html

嵌入式软件
http://blog.csdn.net/embeddedsoft

诚诚恳恳做人踏踏实实编程
http://blog.sina.com.cn/u/1244756857 

和我风格相似的一个blog
http://blogger.org.cn/blog/m…