c - 为什么我在使用 GCC 编译时不必包含我的头文件?

标签 c gcc include

据我了解,为了使用在头文件中声明并在匹配的源文件中定义的函数,所述头文件必须包含在 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/

相关文章:

c - 缓冲标准输入和标准输出

c - 在 C 中编写我自己的管道函数

c++ - Eclipse 不解析 gcc 输出

c++ - 如何使用 -std=c++17(可选、任意、string_view、变体)在 g++ 6.2.0 中包含 C++ 17 header

scala - 在 Scala 中做类似 Python 的 "import"的事情

c - 将参数动态传递给可变函数

c - 为什么我的所有线程都在使用 sleep() 休眠?

gcc - #pragma comment(lib, "xxx.lib") 在 Linux 下等效吗?

gcc - 何时对多个共享库使用某些优化,例如 -fwhole-program 和 -fprofile-generate

c++ - Eclipse C++ 包含错误 : no such file or directory