Tm t1具有不完全类型,不能定义

tm t1 has incomplete type and cannot be defined

本文关键字:不能 定义 类型 不完全 t1 Tm      更新时间:2023-10-16

我必须编写一个程序,在无限循环中调用sleep(60)。在循环中,每隔五次我必须获取当前时间并打印tm_sec字段。

这是我写的:

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main()
{
    struct tm t1;
    int i=0;
    for(;;)
    {
        sleep(60);
        if(i%5==0)
            {
                gettimeofday(&t1,NULL);
                printf("%dn",t1.tm_sec);
            }
        i++;
    }
}

我得到一个错误说aggregate tm t1 has incomplete type and cannot be defined.

我不知道我做错了什么

您需要struct timeval,而不是struct tm。试试这个:

struct timeval t1;

另外,您需要t1.tv_sec,而不是t1.tm_sec

你用错了。从以下两个中任选一个:

#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);

或:

 #include <time.h>
 char *asctime(const struct tm *tm);
 struct tm *gmtime(const time_t *timep);
 struct tm *localtime(const time_t *timep);

gettimeofday接受一个指向timeval而不是tm的指针,给出自1970年以来的时间单位为秒(和微秒)。

如果您想要一个tm,那么您将需要<ctime>中的函数,例如localtime(),来转换timeval的seconds字段。

当我尝试在ESP32库上编译m_wifi.h时,我遇到了同样的问题。

这是可能无法正确配置的c++编译器问题。如果time.h包含在您的代码或库中,并且您得到此编译错误。

在我的例子中,tm结构已经在time.h中声明了。总而言之,我所要做的就是删除我包含的库time.h,并保留ESP32版本ESP32Time.h

我还必须在变量声明部分更正从struct tm timeinfotm timeinfo的代码。