linkage 的作用、或者说限制的是一个翻译单元 translation unit 中,编译器和链接器器如何使用符号。

linkage describes how names can or can not refer to the same entity throughout the whole program or one single translation unit.

  • Internal Linkage
    name 只在当前编译单元的作用域中可见。

    When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.

  • External Linkage
    name 在其他编译单元的作用域中、当前编译单元的作用域中可见。

    When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.


如果不特别指定:

  • 对于 non-const 对象,默认是 extern
  • 对于 const 对象,默认是 static

可以通过 externstatic 关键字,来显式控制符号的 linkage

1
2
3
4
5
6
7
8
9
// in a global / namespace scope
int i; // extern [default]
const int ci; // static [default]

static int si; // static [explicit]
extern const int eci; // extern [explicit]

int f(); // extern [default]
static int f(); // static [explicit]

相比起用 static,建议用匿名命名空间 anonymous namespaces 来控制 linkage,在其中还可以定义 class 等。

1
2
3
4
namespace {
int i; // extern [default] but not accessible from other TU
void f(); // same
} // namespace

可以看看标准,下次一定
https://eel.is/c++draft/basic.link