Search code examples
gccx8632-bit

How to use uint64_t and -m32?


The following code is printing for example 1030432081 (which is wrong) when compiled with gcc -m32 time.c whereas it works fine when compiled without the -m32 flag. Is there any way I can get this to work?

#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();
}

Solution

  • An integer constant has type int if it fits. This is the case for 1000000 in both 32 bits and 64 bits mode.

    Therefore, in 32 bits mode, t.tv_usec, t.tv_sec and 1000000 are all 32 bits and the result, which overflows, too. Only after the computation is the result converted to 64 bits.

    If you cast the constant to 64 bits, then t.tv_sec is promoted to 64 bits before the multiplication and likewise t.tv_usec is promoted to 64 bits before the addition. In effect you force the entire computation to be done in 64 bits. The result, which is correct and already 64 bits, is then stored.