这个程序在名为 localFunc.c 的文件中:
#include <stdio.h>
// int f(int); // Global forward declaration.
int main() {
int f(int); // Local forward declaration.
printf("%d\n", f(1));
}
double f(int i) {
return 1.0;
}
通过 gcc localFunc.c
编译得到:
localFunc.c:10:8: error: conflicting types for ‘f’
double f(int i) {
^
localFunc.c:6:7: note: previous declaration of ‘f’ was here
int f(int); // Local forward declaration.
但是通过g++ localFunc.c
编译,没有报错,运行结果为:4195638
。
注释掉Local forward declaration,并开启Global forward declaration of: int f(int);
,gcc和g++都给出类似上面的错误,如我所料(我) .
所以我的问题是,为什么 g++ 似乎没有在本地声明的函数上看到冲突类型(歧义声明)?
don@HAL:~/UNIX/CS213$ gcc --version
gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
最佳答案
我可以为 C++ 解释这种行为。
来自 C++11 规范,第 3.5 节 [basic.link],第 (7) 段:
When a block scope declaration of an entity with linkage is not found to refer to some other declaration, then that entity is a member of the innermost enclosing namespace. However such a declaration does not introduce the member name in its namespace scope.
因此int f(int)
声明具有全局链接,但没有将名称引入全局命名空间。这或许可以解释为什么 GCC 没有注意到冲突。
更重要的是,第(10)段说:
After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.
您的程序违反了本段的“应”部分,因此其行为未定义。这意味着 GCC 所做的任何事情——例如调用 double foo(int)
函数并将其返回值视为 int——都是规范允许的。此外,不需要诊断。
我不知道 C 对这个案例怎么说;特别是是否需要诊断。
关于c++ - 本地( block )函数 decln 与 defn 返回类型不匹配;在 C++ 中诊断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048089/