最初,我想将struct timeval转换为timespec。
首先,它似乎并不困难,因为在那里提出了一个解决方案: Is there a standard way to convert a struct timeval into a struct timespec?
宏,TIMEVAL_TO_TIMESPEC
应该可以胜任。
如文档(https://www.daemon-systems.org/man/TIMEVAL_TO_TIMESPEC.3.html)所示,它只要求包含sys/time.h
。
但是当我尝试编译时,我仍然得到相同的答案:`警告:隐式声明函数'TIMEVAL_TO_TIMESPEC'[-Wimplicit-function-declaration]
我甚至尝试编译文档中给出的示例:
#include<time.h>
#include <assert.h>
#include<sys/time.h>
static void example(struct timespec *spec, time_t minutes) {
struct timeval elapsed;
(void)gettimeofday(&elapsed, NULL);
_DIAGASSERT(spec != NULL);
TIMEVAL_TO_TIMESPEC(&elapsed, spec);
/* Add the offset for timeout in minutes. */
spec->tv_sec = spec->tv_sec + minutes * 60;
}
int main(){
return 0;
}
编译时我得到:
test.c: In function ‘example’:
test.c:10:2: warning: implicit declaration of function ‘_DIAGASSERT’ [-Wimplicit-function-declaration]
_DIAGASSERT(spec != NULL);
^
test.c:11:2: warning: implicit declaration of function ‘TIMEVAL_TO_TIMESPEC’ [-Wimplicit-function-declaration]
TIMEVAL_TO_TIMESPEC(&elapsed, spec);
^
/tmp/ccqWnL9I.o: In function `example':
test.c:(.text+0x43): undefined reference to `_DIAGASSERT'
test.c:(.text+0x5b): undefined reference to `TIMEVAL_TO_TIMESPEC'
collect2: error: ld returned 1 exit status
我做错了什么?
答案 0 :(得分:1)
您链接到NetBSD手册页。无法保证您在那里阅读的内容与Linux或任何其他操作系统有任何关系。你在开发什么操作系统?
看起来glibc中的宏是标准,这是你在任何Linux系统上使用的C库。但是,如果您检查sys/time.h
文件,则会看到宏由#ifdef
封闭:
#ifdef __USE_GNU
/* Macros for converting between `struct timeval' and `struct timespec'. */
# define TIMEVAL_TO_TIMESPEC(tv, ts) { \
(ts)->tv_sec = (tv)->tv_sec; \
(ts)->tv_nsec = (tv)->tv_usec * 1000; \
}
# define TIMESPEC_TO_TIMEVAL(tv, ts) { \
(tv)->tv_sec = (ts)->tv_sec; \
(tv)->tv_usec = (ts)->tv_nsec / 1000; \
}
#endif
因此,在包含#define __USE_GNU
之前,您需要sys/time.h
才能公开这些宏。正如@alk在评论中指出的那样,通过定义_GNU_SOURCE
可以获得更多信息。您可以阅读有关here的更多信息。