c32bit-64bitportabilitytime-t

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 32-bit but Windows is 32 and 64-bit. 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 64-bit 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?


Solution

  • 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);