Search code examples
c++cmacroslimitc-preprocessor

C Preprocessor Expansion to another object-like macro


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.


Solution

  • 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))