如何在没有头文件的情况下调用像 time() 这样的 C 函数?

und*_*dog 2 c header-files forward-declaration function-declaration c-header

根据我检查的文档,time_t time(time_t *seconds)<time.h>头文件下声明。然而,当我运行这段代码时:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    srand(time(NULL));
    printf("%d",rand());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

不包括<time.h>,它工作正常,或者至少工作。怎么会这样?

Sou*_*osh 6

如果启用编译器警告,它就不能正常工作。如果没有所需的标头,它会发出警告,例如

1347694184/source.c: In function ‘main’:
1347694184/source.c:7:11: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
     srand(time(NULL));
           ^~~~
Run Code Online (Sandbox Code Playgroud)

故事寓意:始终使用适当的编译器设置来发出警告(如果可能,将警告视为错误)。注意警告,你会更安全。