[英]No GCC warning for function with declaration different from definition
C file definition: C文件定义:
#include <stdint.h>
void foo(int i)
{
if(i>0) bar();
}
H file declaration: H文件声明:
#ifndef FILE_H
#define FILE_H
void foo(void);
#endif FILE_H
main: 主要:
#include "file.h"
int main(void)
{
foo();
}
The file.h
is not included in file.c
for some abstraction reasons. 该
file.h
不包括在file.c
某些抽象的原因。 Why isn't GCC generating any warning in this particular case? 为什么在这种特殊情况下,GCC不会生成任何警告?
As noted in comments… 如评论中所述…
In general terms, you must include the header that declares a function both where the function is defined and where it is used. 一般而言, 必须在定义函数和使用函数的位置都包含用于声明函数的标头。 You didn't, so the compiler couldn't warn.
您没有,因此编译器无法发出警告。 Headers are the glue that allow the compiler to do the cross-checking necessary to ensure basic sanity in your code.
标头是使编译器进行必要的交叉检查以确保代码基本健康的粘合剂。
The question claims: 问题声称:
It isn't clear what those abstraction reasons are, but whatever the reasoning, it is faulty. 目前尚不清楚这些抽象原因是什么,但是无论推理如何,都是错误的。 Since the question does not (yet) specify in any more detail what the problem is, we can't help you fix the issues.
由于该问题(尚未)更详细地说明了问题所在,因此我们无法帮助您解决问题。 However, they're spurious — you are doing something wrong.
但是,它们是虚假的-您做错了什么。
Specifically, you must include file.h
in file.c
as well as in main.c
. 具体而言,您必须包括
file.h
在file.c
以及在main.c
。 Otherwise, you don't get the cross-checking you need — or the warning you desire. 否则,您将无法得到所需的交叉检查或期望的警告。 You also need a prototype for
bar()
in file.c
— you shouldn't be calling a function without a prototype (strictly, a non-prototype declaration is sufficient, but you really want a prototype) in scope, and there's no prototype for bar()
in either <stdint.h>
or file.h
. 您还需要
file.c
bar()
的原型-在范围内,没有原型(严格地说,非原型声明就足够了,但是您确实想要一个原型),就不应该调用函数,并且没有原型对于<stdint.h>
或file.h
bar()
。
I compile using GCC and options: 我使用GCC和选项进行编译:
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes …
I don't bother to run the code until that's clean — indeed, the -Werror
means I can't run the code until that's clean because the compilation fails if there is any warning or error. 在干净之前,我不会花时间去运行代码-实际上,
-Werror
意味着直到干净之前,我才能运行代码,因为如果有任何警告或错误,编译会失败。 You can afford to go more stringent if you prefer; 如果愿意,您可以承受更严格的要求。 you shouldn't risk going much less stringent than that.
您不应该冒险比这严格得多。
Note that both C99 and C11 require that a function is declared or defined before it is used. 请注意,C99和C11都要求在使用之前声明或定义函数。 Only the ancient C90 standard permits calling functions that have not been pre-declared or pre-defined.
仅古老的C90标准允许调用尚未预先声明或预先定义的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.