简体   繁体   English

为什么C中函数的原型和定义可能不同?

[英]Why prototype and definition of a function in C may differ?

I'm wondering why this will compile: 我想知道为什么这会编译:

int test();

int main() { return test((void*)0x1234); }
int test(void* data) { return 0; }

Why won't the compiler emit any error/warning about that (I tried clang, gcc)? 为什么编译器不会发出任何错误/警告(我试过clang,gcc)? If I change the return value it won't compile - but the arguments may differ?! 如果我更改返回值它将无法编译 - 但参数可能不同?!

If you change: 如果你改变:

int test();

to: 至:

int test(void);

you will get the expected error: 你会得到预期的错误:

foo.c:4: error: conflicting types for ‘test’
foo.c:1: error: previous declaration of ‘test’ was here

This is because int test(); 这是因为int test(); simply declares a function which takes any parameters (and is therefore compatible with your subsequent definition of test ), whereas int test(void); 简单地声明一个接受任何参数的函数(因此与你后来的test定义兼容),而int test(void); is an actual function prototype which declares a function which takes no parameters (and which is not compatible with the subsequent definition). 是一个实际的函数原型,它声明了一个不带参数的函数(并且与后续定义兼容)。

 int test();

in a function declaration, no parameter means the function takes an unspecified number of arguments. 在函数声明中,没有参数意味着该函数采用未指定数量的参数。

This is different than 这不同于

 int test(void);

which means the function takes no argument. 这意味着该函数不需要参数。

A function declaration with no parameter is the old C style of function declaration; 没有参数的函数声明是旧的C函数声明; C marks this style as obsolescent and discourages its use. C将这种风格标记为过时并且不鼓励使用它。 In short, don't use it. 简而言之,不要使用它。

In your case, you should use a function declaration with the correct parameter declaration: 在您的情况下,您应该使用带有正确参数声明的函数声明:

 int test(void *data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当在c中定义和声明的函数原型不同时,为什么没有警告? - Why there is no warning when function prototype in definition and declaration are not the same in c? C标准 - 函数定义是函数原型吗? - C Standard - Is a function definition a function prototype? function 定义无原型 - function definition without prototype 可以在函数原型中指定返回类型,而在c中的函数定义中可以吗? - Is it okay to specify return type in function prototype and not in function definition in c? 为什么 function 原型在定义后更改是合法的? - Why is it legal to change function prototype after its definition? 使用Doxygen与C,你是否评论函数原型或定义? 或两者? - Using Doxygen with C, do you comment the function prototype or the definition? Or both? 函数定义与原型冲突类型 - function definition conflicting type with prototype 外部函数原型和静态定义 - extern function prototype and static definition 如果在 main() 之后定义的函数中没有返回值,为什么 C 中不需要函数原型? - Why is a function prototype not needed in C if there is no return in a function defined after main()? 预处理器定义与函数原型的使用 - usage of pre processor definition with function prototype
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM