[英]function definition without prototype
when function definition is below, and there is no function prototype.当 function 定义如下时,没有 function 原型。
int main(void)
{
func();
void (*pFunc)(void) = func;
}
void func(void)
{
}
main.c:3:2: warning: implicit declaration of function 'func' is invalid in C99 [-Wimplicit-function-declaration]
func();
^
main.c:4:9: error: incompatible function pointer types initializing 'void (*)(void)' with an expression of type 'int ()' [-Werror,-Wincompatible-function-pointer-types]
void (*pFunc)(void) = func;
^ ~~~~
main.c:4:9: warning: unused variable 'pFunc' [-Wunused-variable]
main.c:7:6: error: conflicting types for 'func'
void func(void)
^
main.c:3:2: note: previous implicit declaration is here
func();
^
2 warnings and 2 errors generated.
I can call a function without function prototpype(ignoring implicit function declaration), but why I can't get the adress of the function? I can call a function without function prototpype(ignoring implicit function declaration), but why I can't get the adress of the function?
warning: implicit declaration of function 'func' is invalid in C99警告:function 'func' 的隐式声明在 C99 中无效
What this actually says is: your code is not valid C.这实际上是说:您的代码无效 C。 There is no telling what it will do and no guarantees.没有人知道它会做什么,也没有保证。
func();
This invokes a non-standard gcc extension known as implicit function declarations/implicit int, which was once part of the C language a very long time ago.这会调用一个非标准的 gcc 扩展,称为隐式 function 声明/隐式 int,很久以前它曾经是 C 语言的一部分。 It means that it will take a guess of the types - always assuming that this is a function returning int
and taking any parameter - same as if you would have typed int func();
这意味着它将猜测类型 - 始终假设这是一个 function 返回int
并采用任何参数 - 就像您输入int func();
一样. . Which is plain wrong and will not work.这是完全错误的,不会起作用。
error: incompatible function pointer types initializing 'void (*)(void)' with an expression of type 'int ()'错误:不兼容的 function 指针类型使用“int ()”类型的表达式初始化“void (*)(void)”
Since we got the function declaration completely wrong above, we get this compiler error.由于我们在上面得到的 function 声明完全错误,我们得到这个编译器错误。 The function pointer is not compatible with the type declared. function 指针与声明的类型不兼容。
error: conflicting types for 'func'错误:“func”的类型冲突
This error happens when we reach the function definition void func (void)
, which collides with the previous definition int func ();
当我们到达 function 定义void func (void)
时会发生此错误,这与之前的定义int func ();
. .
Solution:解决方案:
Fix your compiler so that it gives errors when you write invalid C.修复您的编译器,以便在您编写无效的 C 时出现错误。 See What compiler options are recommended for beginners learning C?请参阅为初学者学习 C 推荐哪些编译器选项?
Move the function declaration outside and above main() and change it to void func (void);
将 function 声明移到 main() 外部和上方,并将其更改为void func (void);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.