键入重载宏

Rom*_*her 7 c macros overloading tostring printf-debugging

我有一堆printf调试助手宏,如果不指定类型那将是非常酷的,你可以做些什么来允许c中的宏重载(如果它在gcc 4.3中可用,则可以是gcc特定的).我想也许是打字,但显然这不起作用.

示例宏(我也有一些ascii终端颜色的东西,我不记得我的头顶)

#ifdef _DEBUG
#define DPRINT_INT(x) printf("int %s is equal to %i at line %i",#x,x,__LINE__);
.
.
.
#else
#define DPRINT_INT(x)
.
.
.
#endif
Run Code Online (Sandbox Code Playgroud)

Ben*_*ott 9

试试这个; 它使用gcc的__builtin方法,并尽可能自动地为您确定类型,并为您提供一个简单的DEBUG宏,您无需指定类型.当然,您可以将typeof(x)与float等进行比较等.

#define DEBUG(x)                                                 \
  ({                                                             \
    if (__builtin_types_compatible_p (typeof (x), int))          \
        fprintf(stderr,"%d\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char))    \
        fprintf(stderr,"%c\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char[]))  \
        fprintf(stderr,"%s\n",x);                                \
    else                                                         \
        fprintf(stderr,"unknown type\n");                        \

  })
Run Code Online (Sandbox Code Playgroud)