portable way to deal with 64/32 bit time_t

前端 未结 5 1481
轻奢々
轻奢々 2020-12-06 05:15

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 Linu

5条回答
  •  情书的邮戳
    2020-12-06 06:00

    If you want to go with the macro specifier, I would recommend one minor tweak. Instead of encapsulating the entire specifier, encapsulate just the modifier:

    #ifdef 64_BIT_TIME
      #define TT_MOD "ll"
    #else
      #define TT_MOD ""
    #endif
    

    and then using it like this:

    printf("current time in seconds is: %" TT_MOD "u", time(0));
    

    The reason why is that while you primarily want the second in decimal, every so often you may want hex (or perhaps you want leading 0's). By only having the modifier there, you can easily write:

    "%" TT_MOD "x"   // in hex
    "%08" TT_MOD "d"  // left pad with 0's so the number is at least 8 digits
    

提交回复
热议问题