Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't PRIu64 work in this code?

Tags:

c++

printf

c++03

As per this answer, I tried printing a uint64_t, but it gives me an error:

error: expected ``)' before 'PRIu64'

Following is the minimal code showing what I am trying to do:

#define __STDC_FORMAT_MACROS #include <inttypes.h> #include <cstdio>  class X {   X() {     uint64_t foo = 0;     printf("%07" PRIu64 ": ", foo);   } };  int main() {} 

This minimal code compiles, but my actual code does not. However, I have tried with the 2 lines inside X::X() exactly the same in my actual code, and that does not work.

What should I look for to debug this further? My actual code also #includes other headers. Could that be causing the problem? Does order of including the headers matter?

Edit PRIu64 is defined as follows on my machine:

# if __WORDSIZE == 64 #  define __PRI64_PREFIX    "l" #  define __PRIPTR_PREFIX   "l" # else #  define __PRI64_PREFIX    "ll" #  define __PRIPTR_PREFIX # endif  # define PRIu64     __PRI64_PREFIX "u" 
like image 798
Masked Man Avatar asked Jan 26 '13 09:01

Masked Man


2 Answers

In C++ the macros are not automatically defined just by including the file.

You need to add the following:

#define __STDC_FORMAT_MACROS 1 

before

#include <inttypes.h> 

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

like image 120
namaenashi Avatar answered Sep 24 '22 03:09

namaenashi


One other possibility for this issue I just found in my own code is if another header already pulls in <inttypes.h> before you define __STDC_FORMAT_MACROS. For example:

Utils.h (Perhaps originally written for C, as it was in our case):

#include <inttypes.h>  // ... Function declarations 

MyFile.cpp:

#include "Utils.h"  #define __STDC_FORMAT_MACROS #include <inttypes.h> 

Since inttypes.h has already been included by Util.h, the compiler doesn't include it again, and doesn't see the declaration of __STDC_FORMAT_MACROS.

The solution is either to edit Utils.h to include #define __STDC_FORMAT_MACROS, or to make sure to define it before doing any includes in MyFile.cpp.

#define __STDC_FORMAT_MACROS #include "Utils.h" #include <inttypes.h> 

The original setup actually compiled just fine on GCC 4.8 on Ubuntu, but failed with an old ltib GCC 4.3 toolchain for PowerPC, which made it all the more perplexing at first.

like image 31
Collin Avatar answered Sep 23 '22 03:09

Collin