Reputation: 41
I have to write a program that calls sleep(60)
in an infinite loop. Every five times through the loop I have to fetch the current time-of-day and print the tm_sec field.
This is what I have written:
#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("%d\n",t1.tm_sec);
}
i++;
}
}
I'm getting an error saying aggregate tm t1 has incomplete type and cannot be defined.
I don't know what I'm doing wrong.
Upvotes: 2
Views: 10848
Reputation: 1911
I had the same issue when trying to compile m_wifi.h
on my ESP32 libraries.
This is the C++ compiler issue that may not configure properly.If time.h
was included in your code or in the library and you get this compilation error.
On my case, the tm
structure was already declared in time.h
. In sum, all I had to do, was to remove the library I had included, the time.h
, and leave the ESP32 version ESP32Time.h
I also had to correct the code from struct tm timeinfo
to tm timeinfo
on the variable declartion section.
Upvotes: 0
Reputation: 254461
gettimeofday
takes a pointer to timeval
, not tm
, giving the time as seconds (and microseconds) since 1970.
If you want a tm
, then you'll need the functions from <ctime>
, such as localtime()
, to convert the seconds field of the timeval
.
Upvotes: 1
Reputation: 477040
You're using it wrong. Pick one of the following two:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
Or:
#include <time.h>
char *asctime(const struct tm *tm);
struct tm *gmtime(const time_t *timep);
struct tm *localtime(const time_t *timep);
Upvotes: 2
Reputation: 385600
You want struct timeval, not struct tm. Try this:
struct timeval t1;
Also, you want t1.tv_sec
, not t1.tm_sec
.
Upvotes: 3