如何使用uint64_t和-m32?

时间:2015-04-30 13:48:50

标签: gcc x86 32-bit

以下代码在使用1030432081编译时打印例如gcc -m32 time.c(这是错误的),而在没有-m32标志的情况下编译时它可以正常工作。有什么方法可以让它发挥作用吗?

#include <sys/time.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

void test() {
  struct timeval t;  
  gettimeofday(&t, NULL);
  uint64_t microseconds = t.tv_usec + t.tv_sec * 1000000;
  printf("%"PRId64, microseconds);
}

int main() {
  test();
}

1 个答案:

答案 0 :(得分:1)

如果适合,则整数常量的类型为int。 32位和64位模式下都是1000000的情况。

因此,在32位模式下,t.tv_usec,t.tv_sec和1000000都是32位,结果也会溢出。只有在计算结果后才将结果转换为64位。

如果将常量转换为64位,则在乘法之前将t.tv_sec提升为64位,同样在添加之前将t.tv_usec提升为64位。实际上,您强制整个计算以64位完成。然后存储正确且已经是64位的结果。