Chinaunix首页 | 论坛 | 博客
  • 博客访问: 367966
  • 博文数量: 715
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-13 14:46
文章分类

全部博文(715)

文章存档

2011年(1)

2008年(714)

我的朋友

分类:

2008-10-13 16:30:23

A compilation unit is C/C++ source code that is compiled and treated as one logical unit. When C/C++ files is compiling, the preprocessor will include the header file recursively. Next the compilation unit will be compiled to object file(.o or .obj). Programs composed of more than one compilation unit can be separately compiled, and later linked to produce the executable program.

Internal Linkage

If a signature is local in its compilation unit, and it can't confilict with the same signature in other compilation units at link phase. We call this signature has internal linkage.

External Linkage

If  a signature will be used to search by other compilation units. We call this signature has external linkage. In other words, if we define this signature in different compilation unit, the compiler will give us an error like: multiple name.

First, I must say all declaration in C++ is neither Internal linkage nor External Linkage, we called it No Linkage. Next I summarized some items to recognise whether a signature is external linkage or not:
1. In a class, the signature of member method defination, the signature of static member method defination and the signature of static member var defination has external linkage.
2. In a namespace(include global namespace), the signature of non-static function defination, the signature of non-static friend function defination and the signature of non-static variable defination  has external linkage.
We can use an example to prove it:
// A.h
class A
{
public:
        int foo();
}
// AA.cpp
#include “A.h“
int A::foo()
{
        return 0; 
}
//AAA.cpp
#include “A.h“
int A::foo()
{
        return 1; 
}
If you compile this code,  you will get the“A::foo already defined in TestEnum.obj“ link error. Because the signature of member function defination has external linkage.If we modify the AAA.cpp file to:
// AAA.cpp
// no code, only include AAA.h
#include “A.h“
There is no error. We can see the signature of class defination has internal linkage.

 I think other case is internal linkage except items that I summarized above, like  the signature of class defination, the signature of union/enum defination etc. If you are a chariness person, you must find all signature with external linkage which can not be located in header file, only in cpp file. Reversely, all signature with internal linkage can be located in header file.


--------------------next---------------------

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