处理 64/32 位 time_t 的便携方式 [英] portable way to deal with 64/32 bit time_t

查看:32
本文介绍了处理 64/32 位 time_t 的便携方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码是在 Windows 和 Linux 上构建的.Linux 在这一点上总是 32 位,但 Windows 是 32 和 64 位.Windows 希望 time_t 为 64 位,而 Linux 仍为 32 位.我很好,除了在某些地方 time_t 值被转换为字符串.所以当 time_T 是 32 位时,它应该用 %d 来完成,当它是 64 位时用 %lld ......这样做的聪明方法是什么?另外:我有什么想法可以找到将 time_t 传递给 printf 样式函数以解决此问题的所有位置吗?

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?

我想出了将 TT_FMT 声明为%d"或%lld",然后将我的 printfs 更改为printf("time: %d, register: blah") 成为 printf("time: " TT_FMT ", register: blah")有没有更好的办法?我如何找到它们?

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?

推荐答案

根据 C 标准,time_t 是一种算术类型,能够表示时间".例如,它可以是 double.(Posix 更明确地提到了这一点,并且还保证time() 返回自 Epoch 以来的秒数——C 标准不保证后者.)

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.)

也许最干净的解决方案是将值转换为您想要的任何类型.您可能需要 unsigned long longunsigned long 之一:

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
", (unsigned long long)t);

这篇关于处理 64/32 位 time_t 的便携方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆