【发布时间】:2021-11-07 18:11:47
【问题描述】:
为什么这段 C 代码在 C99 中编译?我应该阅读什么来了解更多信息?
除非我添加更多文字,否则我无法发布,所以这里有一些废话,因为我认为没有其他要说的了
$ cat m.c
#include <stdio.h>
#include <time.h>
int main() {
struct timespec time;
int res = clock_gettime(CLOCK_REALTIME, &time);
printf("%d %ld %ld\n", res, time.tv_sec, time.tv_nsec);
return 0;
}
$ clang m.c && ./a.out && rm ./a.out
0 1631386905 774654955
$ clang -std=c99 m.c && ./a.out && rm ./a.out
m.c:4:18: error: variable has incomplete type 'struct timespec'
struct timespec time;
^
m.c:4:9: note: forward declaration of 'struct timespec'
struct timespec time;
^
m.c:5:12: warning: implicit declaration of function 'clock_gettime' is invalid in C99 [-Wimplicit-function-declaration]
int res = clock_gettime(CLOCK_REALTIME, &time);
^
m.c:5:26: error: use of undeclared identifier 'CLOCK_REALTIME'
int res = clock_gettime(CLOCK_REALTIME, &time);
^
1 warning and 2 errors generated.
【问题讨论】:
-
这个答案吗? stackoverflow.com/questions/3875197/… c11 有,其他一些东西(posix)也有。只是c99没有。如果使用 c99,则启用其他东西
-
clock_gettime不是 C99 的一部分,代码可以使用 GNU99 扩展-std=gnu99或#define _POSIX_C_SOURCE 200112L宏进行编译 -
“在 C99 中无效”是因为在未启用 POSIX 功能测试宏的情况下,
<time.h>不包含clock_gettime的声明。在 C99 之前,即使没有声明,使用函数也是合法的(尽管通常是错误的);编译器假定函数的隐式声明返回int并采用未指定的参数。在 C99 中,这是未定义的行为,但 GCC 在发出警告后仍会提供较旧的行为。无论如何,您不想要任何这些;正确的解决方法是定义功能测试宏并从<time.h>获取正确的声明。
标签: c99 libc system-clock