【问题标题】:How to print the time in c/unix with gettimeofday()如何使用 gettimeofday() 在 c/unix 中打印时间
【发布时间】:2016-02-20 23:56:07
【问题描述】:

我正在尝试以 21-02-2016 00:50:00 的格式写入时间,但有一些我无法解决的错误。同样在主函数中,我调用了PrintTime(),我在主函数中得到了一个未定义的引用错误,这可能是因为这段代码。

void PrintTime()
{
  struct timeval tv;
  time_t nowtime;
  struct tm *nowtm;
  char tmbuf[64]

  gettimeofday(&tv, NULL);
  nowtime = tv.tv_sec;
  nowtm = localtime(&nowtime);
  strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
  free(tmbuf);
}

我尝试执行这里是我得到的错误列表:

Q3.c:67:7: warning: assignment makes pointer from integer without a cast
 nowtm = localtime(&nowtime);
       ^
Q3.c:68:1: warning: incompatible implicit declaration of built-in function ‘strftime’
 strftime(tmbuf, sizeof tmbuf, "%d-%d-%d %d:%d:%d", nowtm);
 ^
/tmp/ccwQwMjE.o: In function `main':
Q3.c:(.text+0x102): undefined reference to `PrintTime'

【问题讨论】:

  • 我猜你没有包含正确的标题,也没有使用PrintTime 函数链接到文件。为了获得更好的答案,需要Minimal Complete Verifiable Example,以及用于构建程序的命令行。
  • 除非您有充分的理由使用“DD-MM-YYYY HH:MM:SS”,否则请使用 ISO 8601 标准格式“YYYY-MM-DD HH:MM:SS”。这是一个国际标准,没有歧义,而且分类正确。

标签: c unix ubuntu time


【解决方案1】:

您的代码中应该包含#include <time.h>

/* PrintTime.h */
#ifndef PRINTTIME_H
#define PRINTTIME_H
...
#include <time.h>
...

void PrintTime(){

}

还有main.c

/* main.c */
...
#include <PrintTime.h>
...

int main() {
 ...
 return 0;
}

编译

% cc main.c -o main -I_path_to_PrintTime_h_file

【讨论】:

    【解决方案2】:

    您在char tmbuf[64] 之后忘记了;free(tmbuf); 是错误的,因为 tmbuff 被声明为堆栈而不是堆。再次修改编译。确保您已经加入

    #include <sys/time.h>
    #include <time.h>
    

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      相关资源
      最近更新 更多