据我了解,为了使用在头文件中声明并在匹配的源文件中定义的函数,所述头文件必须包含在 main() 之前。那么为什么下面的编译和运行很好使用:
gcc -o hello hellomain.c hello.c
hellomain.c
int main(int argc, char *argv[])
{
helloPrint();
return 0;
}
你好.h
#ifndef hello_h
#define hello_h
void helloPrint();
#endif
你好.c
#include <stdio.h>
void helloPrint()
{
printf("Hello, World!");
}
这显然是一个非常简化的示例,但它说明了我的问题;为什么我不必在“hellomain.c”中包含“hello.h”?谢谢!
最佳答案
当使用没有原型(prototype)的函数时,编译器会对它的返回类型和它接受的参数做出某些假设。在这种情况下,这些假设恰好有效,即使它假设函数返回 int
。
正如 Eric Postpischil 在评论中指出的那样,强烈建议不要省略原型(prototype),因为它会导致细微的错误。您应该始终确保您的函数调用具有可用的所需原型(prototype),最好包括它们相应的 header 。
关于c - 为什么我在使用 GCC 编译时不必包含我的头文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14446682/