问题
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 #include
s 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"
回答1:
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.
回答2:
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"
回答3:
PRIu64
is not defined where you use it.
Replace it with the string "llu"
and your code will compile (but that is not a fix, it just demonstrates the problem)
Maybe the include
is missing. Maybe over zealos include guards and it being included without the magic token block the define
. Maybe your pch is busted.
回答4:
If you are on android JNI platform. Put this in your Android.mk:
LOCAL_CPPFLAGS := -D__STDC_FORMAT_MACROS
来源:https://stackoverflow.com/questions/14535556/why-doesnt-priu64-work-in-this-code