DCL36-C. 不要声明链接类型冲突的标识符

2021-09-26  本文已影响0人  大唐游子

DCL36-C. 不要声明链接类型冲突的标识符

链接可以使标识符在不同的作用域中声明,或者在同一个作用域中声明多次(这些声明指向同一个对象或函数)。标识符可以被分为外部链接内部链接无链接。这三类链接具有以下特征 [Kirch-Prinz 2002]:

根据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

不遵从规范的代码示例

在这个不遵从规范的代码示例中,i2i5被定义为既是内部又是外部链接属性。进一步使用这两个标识符会导致未定义行为


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;
}
上一篇下一篇

猜你喜欢

热点阅读