Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

portable way to deal with 64/32 bit time_t

I have some code which is built both on Windows and Linux. Linux at this point is always 32bit but Windows is 32 and 64bit. Windows wants to have time_t be 64 bit and Linux still has it as 32 bit. I'm fine with that, except in some places time_t values are converted to strings. So when time_T is 32 bit it should be done with %d and when it is 64bit with %lld... what is the smart way to do this? Also: any ideas how I may find all places where time_t's are passed to printf-style functions to address this issue?

edit: I came up with declaring TT_FMT as "%d" or "%lld" and then changing my printfs as in printf("time: %d, register: blah") to be printf("time: " TT_FMT ", register: blah") Is there a better way? And how do I find them all?

like image 545
MK. Avatar asked Mar 18 '10 03:03

MK.


1 Answers

According to the C standard, time_t is an arithmetic type, "capable of representing times". So, it could be double for example. (Posix mentions this more explicitly, and also guarantees that time() returns the number of seconds since the Epoch—the latter is not guaranteed by the C standard.)

Maybe the cleanest solution is to convert the value to whatever type you want. You may want one of unsigned long long or unsigned long:

printf("%llu\n", (unsigned long long)t);
like image 120
Alok Singhal Avatar answered Oct 07 '22 18:10

Alok Singhal