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

标签 c++ c macros limit c-preprocessor

我有如下代码(混合 C/C++ 应用程序)

#include <stdint.h>
#define BUFFER_SIZE UINT16_MAX

我原以为 BUFFER_SIZE 是 (65535) 就像 UINT16_MAX 是在 stdint.h 中定义的,但编译器却提示 UINT16_MAX 不是定义。显然,宏展开并没有像我希望的那样发生。

我可以自己将其定义为 (65535),但想知道为什么这不起作用。

对一些评论的回应:

  • 我的编译器确实支持 uint16_t 类型并且 UINT16_MAX 在 stdint.h 中定义

  • 有人提到定义 __STDC_LIMIT_MACROS - 我曾尝试在包含 stdint.h 之前定义它,但没有效果。

回答

所以它是 __STDC_LIMIT_MACROS 但更复杂。

  1. #define 在头文件中(包括 stdint.h)
  2. 在包含 stdint.h 之前,我在此文件中有#define __STDC_LIMIT_MACROS
  3. 我将该头文件包含在另一个源文件中。这个其他源文件也#include stdint.h 并在包含我的标题之前这样做。因此,当首次包含 stdint.h 时,未定义 __STDC_LIMIT_MACROS

我的解决方案只是将 -D__STDC_LIMIT_MACROS 添加到我的编译器参数中。

最佳答案

因为您似乎在使用 C++,您可能会这样做:

#define __STDC_LIMIT_MACROS

来自最近的 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))

关于c++ - C 预处理器扩展到另一个类似对象的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17239124/

相关文章:

c++ - sockaddr_in 中的 sin_port

C 位数组宏,谁能解释一下这些是如何工作的?

c - 如何编写将 float* 转换为 float_ptr 的 C 宏?

c - 什么时候在 C 中使用指向指针的指针来打字双关是合法的?

java - c/c++/java/PHP有闭包吗?

ios - ELEVENWORDINLINE什么时候用呢?

c++ - boost::assign 与 std::map

c++ - join() 抛出 thread_resource_error?

c++ - CMake 链接问题 : undefined reference to QPushButton

c++ - 从构造函数调用耗时函数