2

最初,我想将 struct timeval 转换为 timespec 。

起初,这似乎并不困难,因为那里提出了一个解决方案: 是否有一种标准方法可以将 struct timeval 转换为 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

我做错了什么?

4

1 回答 1

1

您链接到 NetBSD 手册页。无法保证您在那里阅读的内容与 Linux 或任何其他操作系统有任何关系。您正在开发什么操作系统?

看起来宏在 glibc 中标准的,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. 您可以在此处阅读更多相关信息。

于 2018-01-05T16:27:47.277 回答