我想知道如果下面的C代码段,其中的f
定义不能重复f
是static
联动的,是正确的声明和定义之间的联动:按照
static int f(int);
int f(int x) { return x; }
锵不排放任何警告它。我读了C11标准的条款6.7.1,但没有找到我的问题的答案。
可以想象出更多的问题,例如下面的t1.c和t2.c,如果答案一般足以适用于其中一些,这将是很好的,但我只是真的关注上面的第一个例子。
~ $ cat t1.c
static int f(int);
int f(int);
int f(int x) { return x; }
~ $ clang -c -std=c99 -pedantic t1.c
~ $ nm t1.o
warning: /Applications/Xcode.app/…/bin/nm: no name list
~ $ cat t2.c
int f(int);
static int f(int);
int f(int x) { return x; }
~ $ clang -c -std=c99 -pedantic t2.c
t2.c:3:12: error: static declaration of 'f' follows non-static declaration
static int f(int);
^
t2.c:1:5: note: previous declaration is here
int f(int);
^
1 error generated.
我不明白为什么第二个片段需要诊断。与@BlueMoon引用的相反,这个“唯一”似乎是UB。 – 2014-10-08 14:20:02
@JensGustedt:谢谢,我想知道,如果这是违反约束的话,UB在蓝月的答案中提到的UB应该如何发生,这就是答案。我的理解是否正确,通常,拒绝在UB上编译(在语句中)意味着编译器必须能够确定所讨论的代码是否可达,但这不适用于此,因为我们正在处理(文件范围)声明? – mafso 2014-10-08 14:40:11
是的,这里是没有执行的代码,所以可达性没有多大意义:)这里的UB意味着整个程序从一开始就具有UB。可能基本上是因为标识符的链接可能出错了。尽管如此,将UB作为UB是有点跛脚的,这在编译时很容易检测到,所以我认为违反约束条件是有条件的。 – 2014-10-08 15:01:43