extern “C” const __declspec(selectany)

来源:互联网 发布:守望先锋 低配优化 编辑:程序博客网 时间:2024/06/06 06:53

extern“C” const __declspec(selectany)

在微软有一段定义

DEFINE_GUID(name,l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) /

    extern “C” const GUID  __declspec(selectany) name /

         … …

为什么要用Extern “C” const__declspec(selectany)这三个符号呢?

首先看一下需求。需求是定义一个变量是外部链接的并且是const的。外部链接指一个cpp里面的变量在另一个cpp里面能看到。这样的话内存只占一份。Const 的就好理解了。

尝试以下定义方式

1如果定义为

const int i=0;  // 非外部链接的

原因请看c++标准文档

A name having namespace scope has internal linkage if it is thename of

a variable thatis explicitly declared const and neither explicitly declared extern norpreviously declared to have external linkage

2,如果定义为

int __declspec(selectany) i=0;       //const

3,如果定义为

const int __declspec(selectany) i=0;    // 出错,const之后,i不是全局的,__declspec(selectany)必须作用于外部链接的,请看msdn的描述,报错信息如下

// error error C2496: 'i' : 'selectany' can only be applied todata items with external linkage

4,如果定义为

extern const int i=0;

// error LNK2005: "int const i" (?i@@3HB) already definedin SomeImp.obj

5,如果定义为

extern "C" const int i=0;

// error LNK2005: _i already defined in SomeImp.obj

总结如下

3个符号任选两个有3种组合方式。(exertn extern “C”视为一个符号)。它们是

extern const int i=0; (不能用,见上面的45)

const int __declspec(selectany) i =0; (不能用,见上面的3)

extern int  __declspec(selectany)i =0; (不满足const的要求)

在所有的尝试失败之后解决方法:

extern const int __declspec(selectany) i=0;

或者

extern "C" const int __declspec(selectany) i=0;

这样它满足需求,既是外部链接的,又是const的,编译都没问题。为什么选择的是extern "C"而不是extern?这是为了链接的需要。假设一个someImp.c(注意是.c,用c编译链接的)用了i,它定义为extern const int __declspec(selectany) i=0;就回链接失败,定义为extern "C" const int __declspec(selectany) i=0;才能链接成功。

后注:

Extern的用法有点怪异。Extern一般表示的是一个变量的存储属性,表示该变量存在另一个地方,你不用关心它的存储。当用extern的时候初始化了又是什么含义呢?请看c++文档

[Note: The extern keyword can also be used in explicit-instantiationsand

linkage-specfications,but it is not a storage-class-specifier insuch contexts. —endnote ]

原创粉丝点击