Con*_*tor 2 c c++ function-declaration
当struct bar以下代码中没有可见的声明或定义时,它会成功编译为C++而不是C:
void foo(struct bar* p);
void foo(struct bar* p){}
int main(){}
Run Code Online (Sandbox Code Playgroud)
编译为C:时出现错误消息error: conflicting types for 'foo'.
谁能解释这种行为?
我已经与两个尝试这样铛++ 3.4和克++ 4.8.2用-Wall -Wextra -pedantic-errors标志和任一-std=c99或-std=c++03C和分别C++.
Fre*_*Foo 10
让我们通过省略声明和无用来简化程序main:
void foo(struct bar* p){}
Run Code Online (Sandbox Code Playgroud)
编译器看到struct bar,尚未定义.来自GCC 4.8.2的错误消息解释了它接下来会做什么:
a.c:1:17: warning: ‘struct bar’ declared inside parameter list [enabled by default]
void foo(struct bar* p){}
^
a.c:1:17: warning: its scope is only this definition or declaration, which is probably not what you want [enabled by default]
Run Code Online (Sandbox Code Playgroud)
所以现在假设struct bar它只存在于定义中foo.但是,代码完美地编译.
添加函数原型时:
void foo(struct bar* p);
void foo(struct bar* p){}
Run Code Online (Sandbox Code Playgroud)
警告变成:
a.c:1:17: warning: ‘struct bar’ declared inside parameter list [enabled by default]
void foo(struct bar* p);
^
a.c:1:17: warning: its scope is only this definition or declaration, which is probably not what you want [enabled by default]
a.c:3:17: warning: ‘struct bar’ declared inside parameter list [enabled by default]
void foo(struct bar* p){}
^
a.c:3:6: error: conflicting types for ‘foo’
void foo(struct bar* p){}
^
a.c:1:6: note: previous declaration of ‘foo’ was here
void foo(struct bar* p);
^
Run Code Online (Sandbox Code Playgroud)
与之前一样,编译器struct bar为原型组成了一个新的未定义类型,另一个用于函数定义.所以原型foo及其定义指的是不同的类型,两者都命名struct bar.它们不匹配,因此错误.
解决方案是先向前声明struct:
struct bar;
void foo(struct bar* p);
void foo(struct bar* p){}
Run Code Online (Sandbox Code Playgroud)
这编译没有警告.