4
votes

I have code like the following (Mixed C/C++ application)

#include <stdint.h>
#define BUFFER_SIZE UINT16_MAX

I was expecting BUFFER_SIZE to be (65535) like UINT16_MAX is defined in stdint.h but instead the compiler complains the UINT16_MAX was not defined. Obviously the macro expansion isn't happening as I would like.

I could just define it myself to (65535) but would like to know why this doesn't work.

Response to a couple comments:

  • My compiler does support the uint16_t type and UINT16_MAX is defined in stdint.h

  • One person mentioned defining __STDC_LIMIT_MACROS - I have tried defining this before including stdint.h to no effect.

ANSWER

So it was the __STDC_LIMIT_MACROS but more complicated.

  1. The #define was in a header file (which included stdint.h)
  2. I had #define __STDC_LIMIT_MACROS in this file prior to including stdint.h
  3. I included that header file in another source file. This other source file also #include stdint.h and did so prior to including my header. Therefore when stdint.h was first included __STDC_LIMIT_MACROS was not defined

My solution was just to add -D__STDC_LIMIT_MACROS to my compiler arguments.

2
Try including limits.h - VoidPointer
@VoidPointer - UINT_MAX is defined in limits.h, but UINT16_MAX is defined in stdint.h (if the implementation provides an exact 16-bit unsigned type). - Pete Becker
Does your compiler support uint16_t? That's not required to exist. - Pete Becker
@VoidPointer - sure it does. "Maximum values of exact-width unsigned integer types: {UINTN_MAX} Exactly 2^N -1". Replace N with the number of bits. - Pete Becker

2 Answers

6
votes

As you seem to be using C++ you might do:

#define __STDC_LIMIT_MACROS

From /usr/include/stdint.h of a recent Debian:

/* The ISO C99 standard specifies that in C++ implementations these
   macros should only be defined if explicitly requested.  */
#if !defined __cplusplus || defined __STDC_LIMIT_MACROS

...

/* Maximum of unsigned integral types.  */
# define UINT8_MAX              (255)
# define UINT16_MAX             (65535)
# define UINT32_MAX             (4294967295U)
# define UINT64_MAX             (__UINT64_C(18446744073709551615))
3
votes

If you are including the C header from a C++03 file, then you will need to define __STDC_LIMIT_MACROS before including the header; otherwise it may not define these macros.

If you're using C++11, then include the C++ header <cstdint> instead.