我想进一步了解函数my_func()是否暴露给下面的简化示例的链接器。基础知识是优先的,是前向声明还是声明?
我猜是前向声明,但是为什么呢?有人可以解释一下吗?到K&R很好
static int my_func(void);
<Use my_func here>
int my_func(void)
{
return 1;
}
如果将示例修改为该示例,则该怎么办
static int my_func(void);
int my_func(void);
<Use my_func here>
int my_func(void)
{
return 1;
}
此
static int my_func(void);
已经是具有内部链接的函数声明。
所以下面的声明
int my_func(void);
是多余的。
这些声明
static int my_func(void);
int my_func(void);
相当于
static int my_func(void);
extern int my_func(void);
来自C标准(6.2.2标识符的链接)
5 如果函数标识符的声明没有存储类说明符,它的链接被确定为完全一样用存储类说明符extern声明的。
和
4 对于使用存储类说明符extern声明的标识符在该标识符的先前声明为可见的31)如果先前声明指定内部还是外部链接,在以后的声明中标识符的链接是与先前声明中指定的链接相同。如果没有先前声明声明可见,或者如果先前的声明未指定链接,则标识符具有外部链接。
因此,此代码段中的代码
static int my_func(void);
int my_func(void);
<Use my_func here>
int my_func(void)
{
return 1;
}
您具有与internal linkage
和声明相同功能的三个声明
int my_func(void);
如前所述是多余的。
这意味着该功能在其他翻译单元中不可见。或者,如果将带有存储类说明符static的函数声明放在标头中,则包含标头的每个转换单元都具有其自己的同名函数。
如果您愿意写类似的东西
int my_func(void);
static int my_func(void);
然后,行为未定义,因为相同的名称被定义为具有外部和内部链接。
来自C标准(6.2.2标识符的链接)
7如果在翻译单元中,相同的标识符出现在两个内部和外部链接,行为是不确定的。