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

C++C

C++ Problem Overview


I wrote a very simple test code of printf uint64_t:

#include <inttypes.h>
#include <stdio.h>

int main()
{
  uint64_t ui64 = 90;
  printf("test uint64_t : %" PRIu64 "\n", ui64);
  return 0;
}

I use ubuntu 11.10 (64 bit) and gcc version 4.6.1 to compile it, but failed:

main.cpp: In functionint main()’:
main.cpp:9:30: error: expected ‘)’ beforePRIu64main.cpp:9:47: warning: spurious trailing ‘%’ in format [-Wformat]

C++ Solutions


Solution 1 - C++

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Solution 2 - C++

When compiling memcached under Centos 5.x i got the same problem.

The solution is to upgrade gcc and g++ to version 4.4 at least.

Make sure your CC/CXX is set (exported) to right binaries before compiling.

Solution 3 - C++

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - C++WillView Answer on Stackoverflow
Solution 2 - C++Anders EliassonView Answer on Stackoverflow
Solution 3 - C++vitautView Answer on Stackoverflow