External Linkage V.S Internal Linkage

 
Compilation Units

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值