当前位置: 代码迷 >> 综合 >> 关于使用clock_gettime函数报错的问题
  详细解决方案

关于使用clock_gettime函数报错的问题

热度:20   发布时间:2024-01-17 15:32:18.0

在linux下写C程序的时候,出现了这个错误

error: ‘CLOCK_REALTIME’ undeclared (first use in this function)#  define CLOCK_MONOTONIC CLOCK_REALTIME^
note: in expansion of macro ‘CLOCK_MONOTONIC’if (clock_gettime(CLOCK_MONOTONIC,&t) != 0) {^
note: each undeclared identifier is reported only once for each function it appears in#  define CLOCK_MONOTONIC CLOCK_REALTIME^
note: in expansion of macro ‘CLOCK_MONOTONIC’if (clock_gettime(CLOCK_MONOTONIC,&t) != 0) {

这里面的错误有好几个原因

其一:是要看是否包含clock_gettime()函数的头文件,#include <time.h>,这个可以再man手册里面查询;

其二:是要在程序开始加上如下代码(也就是main函数之前,因为这个是宏定义):

#ifdef _GNU_SOURCE
# undef  _XOPEN_SOURCE
# define _XOPEN_SOURCE 600
# undef  _XOPEN_SOURCE_EXTENDED
# define _XOPEN_SOURCE_EXTENDED 1
# undef  _LARGEFILE64_SOURCE
# define _LARGEFILE64_SOURCE 1
# undef  _BSD_SOURCE
# define _BSD_SOURCE 1
# undef  _SVID_SOURCE
# define _SVID_SOURCE 1
# undef  _ISOC99_SOURCE
# define _ISOC99_SOURCE 1
# undef  _POSIX_SOURCE
# define _POSIX_SOURCE 1
# undef  _POSIX_C_SOURCE
# define _POSIX_C_SOURCE 200112L
# undef  _ATFILE_SOURCE
# define _ATFILE_SOURCE 1
#endif

其三:在编译 程序时写的makefile中要加上如下语句:-D _GNU_SOURCE

make:gcc -D _GNU_SOURCE  rnnoise_demo.c rnnoise.c -o main -lm -std=c99

上面代码中 -lm 是为了编译数学函数sinf(),conf()等,防止其报错。 数学函数头文件 #include <math.h>。