使用時間函數 gettimeofday() 時報錯 “error: storage size of ‘tv’ isn’t known”,代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
int main()
{
struct tim tv;
struct timezone tz;
gettimeofday (&tv , &tz);
printf("===> tv_sec1: %ld\n", tv.tv_sec);
printf("===> tv_usec1: %ld\n", tv.tv_usec);
sleep(3);
gettimeofday (&tv , &tz);
printf("===> tv_sec2: %ld\n", tv.tv_sec);
printf("===> tv_usec2: %ld\n", tv.tv_usec);
return 0;
}
使用 gcc 編譯報錯:
test.c: In function ‘main’:
test.c:10: error: storage size of ‘tv’ isn’t known
於是仔細查了 gettimeofday 函數,發現函數的定義與我記得的有出入,正確的如下:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
參考:
http://man7.org/linux/man-pages/man2/settimeofday.2.html
於是把
struct tim tv;
換成
struct timeval tv;
即可。
博主所有文章已轉自私人博客 Joe 的個人博客,謝謝關注!