简体   繁体   English

C预处理器扩展到另一个类似对象的宏

[英]C Preprocessor Expansion to another object-like macro

I have code like the following (Mixed C/C++ application) 我有以下代码(混合C / C ++应用程序)

#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. 我期待BUFFER_SIZE为(65535),就像在stdint.h中定义了UINT16_MAX ,但是编译器抱怨UINT16_MAX没有被定义。 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. 我可以自己定义它(65535),但想知道为什么这不起作用。

Response to a couple comments: 回复几条评论:

  • My compiler does support the uint16_t type and UINT16_MAX is defined in stdint.h 我的编译器支持uint16_t类型, UINT16_MAX在stdint.h中定义

  • One person mentioned defining __STDC_LIMIT_MACROS - I have tried defining this before including stdint.h to no effect. 有人提到定义__STDC_LIMIT_MACROS - 在尝试包含stdint.h之前我已经尝试过定义它。

ANSWER 回答

So it was the __STDC_LIMIT_MACROS but more complicated. 所以它是__STDC_LIMIT_MACROS但更复杂。

  1. The #define was in a header file (which included stdint.h) #define位于头文件中(包括stdint.h)
  2. I had #define __STDC_LIMIT_MACROS in this file prior to including stdint.h 在包含stdint.h之前,我在此文件中有#define __STDC_LIMIT_MACROS
  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. 这个其他源文件也包括#include stdint.h,并在包含我的标题之前这样做了。 Therefore when stdint.h was first included __STDC_LIMIT_MACROS was not defined 因此,当首次包含stdint.h时__STDC_LIMIT_MACROS未定义

My solution was just to add -D__STDC_LIMIT_MACROS to my compiler arguments. 我的解决方案只是将-D__STDC_LIMIT_MACROS添加到我的编译器参数中。

As you seem to be using C++ you might do: 正如您似乎在使用C ++,您可能会这样做:

#define __STDC_LIMIT_MACROS

From /usr/include/stdint.h of a recent Debian: 来自最近的Debian的/usr/include/stdint.h

/* 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))

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; 如果要包含C ++ 03文件中的C头,则需要在包含头之前定义__STDC_LIMIT_MACROS ; otherwise it may not define these macros. 否则它可能无法定义这些宏。

If you're using C++11, then include the C++ header <cstdint> instead. 如果您使用的是C ++ 11,那么请包含C ++标头<cstdint>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM