【问题标题】:Detect whether a macro is void检测宏是否无效
【发布时间】:2018-09-05 18:18:38
【问题描述】:

我试图在编译时检测宏是否为void。我知道宏定义了一个类型,但它可以是任何类型(结构、指针、数组、函数指针等),我需要弄清楚这个类型是否是void。到目前为止,我已经设法使它适用于整数和浮点类型(下面有问题的宏名为type)。

#define void +1
#define unsigned +0
#define signed +0
#define long +0
#define short +0
#define const +0
#define volatile +0

#if (type == void)
# warning "is void"
#else
# warning "is not void"
#endif

#undef volatile
#undef const
#undef short
#undef long
#undef signed
#undef unsigned
#undef void

代码基于此描述:https://gcc.gnu.org/onlinedocs/cpp/If.html#If

有没有办法在一般情况下(在所有类型中)在编译时检测 void?

【问题讨论】:

  • type 是什么,你真的不应该为基本类型定义标记。
  • 您的#define 都会导致未定义的行为
  • 你希望#define type const unsigned long int发生什么?

标签: c macros c-preprocessor c99


【解决方案1】:

使用与保留字一致的名称定义宏是未定义的行为。

以下是正确执行此操作的方法。

#if !defined(T)             // just for testing
#define T void
#endif

#define is_void   0
#define is_int    1
#define is_char   2
#define is_double 3

#define cat(x,y) cat2(x,y)
#define cat2(x,y) x##y

#if cat(is_, T) == is_void  // use the test
#error "type is void"       // or do something useful
#else
#error "type is not void"   // or do something useful
#endif

测试:

> gcc -E test.c -DT=void
# 1 "test.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "test.c"
test.c:14:2: error: #error "type is void"
 #error "type is void"
  ^~~~~

> gcc -E test.c -DT=int
# 1 "test.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "test.c"
test.c:16:2: error: #error "type is not void"
 #error "type is not void"
  ^~~~~

这当然只适用于语法标识符的标记,因此您无法检查 int* 或类似的东西。

【讨论】:

    【解决方案2】:

    既然你指的是gcc的文档,你可以使用它的内置函数:

    #define IS_VOID(x) __builtin_types_compatible_p(x, void)
    

    【讨论】:

      【解决方案3】:

      使用 C11 和静态断言的替代方法:

      #define IS_VOID(x) _Static_assert(_Generic((x*)0,       \
                                                 void*: 0,    \
                                                 default: 1), \
                                        "void type " #x " detected")
      
      ...
      
      #define T void
      
      ...
      
      IS_VOID(T);
      

      gcc 上的编译器消息:

      错误:静态断言失败:“检测到无效类型 T”

      代码使用void* 而不是void,因为void 是不完整的类型,因此不能存在于_Generic 表达式中。

      【讨论】:

        猜你喜欢
        • 2021-11-18
        • 2015-07-21
        • 1970-01-01
        • 2014-02-23
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-24
        相关资源
        最近更新 更多