c64-bitc99format-specifiersstdint

In C, is it true that PRId64 is defined if-and-only-if int64_t is available?


I want to portably work with 64-bit signed types in C. However - I know that int64_t is not guaranteed to be defined. I can use some preprocessor magic in my build system generation (e.g. CMake's check_type_size()) to get preprocessor definitions telling me whether I can use it or not. However - we do have the PRId64 format specifier, which we are to use for passing int64_t values to printf()-like functions. Can I, therefore, use the definedness of PRId64 as a proxy for determining whether or not int64_t is available?


Solution

  • You can test for the existence of the optional macros that may be provided by <stdint.h>, such as INT64_MIN or INT64_MAX that are defined if and only if the corresponding optional types such as int64_t are implemented.

    From C99 §7.18 par. 4, and C11/C17 §7.20 par. 4, and C23 §7.22.1 par. 4:

    For each type described herein that the implementation provides, <stdint.h> shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, <stdint.h> shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as "required", but may not provide any of the others (described as "optional").

    The standard does not currently require that the PRId64 macro will not be defined by <inttypes.h> if int64_t is not implemented, and similarly for the other optional types defined by <stdint.h>.

    In summary: