DCL36-C. 不要声明链接类型冲突的标识符
链接可以使标识符在不同的作用域中声明,或者在同一个作用域中声明多次(这些声明指向同一个对象或函数)。标识符可以被分为外部链接,内部链接或无链接。这三类链接具有以下特征 [Kirch-Prinz 2002]:
-
外部链接(External linkage): 一个具有外部链接属性的标识符在整个程序中(即所有属于该程序的编译单元和库)都表示同一个对象或函数。链接器可以链接到该标识符。当另外一个同样的标识符被声明时,链接器会将该标识符 指定到同一个对象或函数。
-
内部链接(Internal linkage): 一个具有内部链接属性的标识符在指定的翻译单元中表示通过一个对象或函数。链接器不知道内部链接属性标识符的任何信息。这些标识符只对翻译单元内部可见。
-
无链接(No linkage): 如果一个标识符时无链接的,那么再声明一个该标识符都会声明一个新的对象或类型.
根据C语言标准,6.2.2 [ISO/IEC 9899:2011], 链接被定义如下:
If the declaration of a file scope identifier for an object or a function contains the storage class specifier
static
, the identifier has internal linkage.For an identifier declared with the storage-class specifier
extern
in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier
extern
. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier
extern
.
在某个翻译单元中使用一个既是内部又是外部链接类型的标识符会导致 未定义行为(参见未定义行为 8)。一个翻译单元包含源文件及其头文件,以及所有通过预编译指令#include
包含的源文件。
下面这个表格标识了在一个单独的翻译单元中声明了两次的对象的链接属性。列表示第一次声明,行表示再次声明。
DCL36-C_table.png不遵从规范的代码示例
在这个不遵从规范的代码示例中,i2
和i5
被定义为既是内部又是外部链接属性。进一步使用这两个标识符会导致未定义行为。
int i1 = 10; /* Definition, external linkage */
static int i2 = 20; /* Definition, internal linkage */
extern int i3 = 30; /* Definition, external linkage */
int i4; /* Tentative definition, external linkage */
static int i5; /* Tentative definition, internal linkage */
int i1; /* Valid tentative definition */
int i2; /* Undefined, linkage disagreement with previous */
int i3; /* Valid tentative definition */
int i4; /* Valid tentative definition */
int i5; /* Undefined, linkage disagreement with previous */
int main(void) {
/* ... */
return 0;
}
符合规范的解决方案
这个符合规范的方案不包含链接类型冲突的定义:
int i1 = 10; /* Definition, external linkage */
static int i2 = 20; /* Definition, internal linkage */
extern int i3 = 30; /* Definition, external linkage */
int i4; /* Tentative definition, external linkage */
static int i5; /* Tentative definition, internal linkage */
int main(void) {
/* ... */
return 0;
}
网友评论