我可以对宏使用哪些技巧?[关闭]
-
19-08-2019 - |
题
在我们的遗留代码以及现代代码中,我们使用宏来执行漂亮的解决方案,例如代码生成等。我们同时利用 #
和 ##
运营商。
我很好奇其他开发人员如何使用宏来做很酷的事情(如果他们使用宏的话)。
解决方案
在C,这是常见的定义做一些东西越来越逐字参数宏,并在同一时间定义功能,能够透明地得到它的地址。
// could evaluate at compile time if __builtin_sin gets
// special treatment by the compiler
#define sin(x) __builtin_sin(x)
// parentheses avoid substitution by the macro
double (sin)(double arg) {
return sin(arg); // uses the macro
}
int main() {
// uses the macro
printf("%f\n", sin(3.14));
// uses the function
double (*x)(double) = &sin;
// uses the function
printf("%f\n", (sin)(3.14));
}
其他提示
最酷宏是:断言,包括防护装置,__FILE__,__LINE__结果。 避免在代码中使用其他宏观。
修改强>结果 使用宏,只有当你不具备法律解决W / O他们。
有也是X宏成语其可用于DRY和简单的代码生成有用:
一在头部限定使用的尚未定义强>宏gen.x一样的表:
/** 1st arg is type , 2nd is field name , 3rd is initial value , 4th is help */
GENX( int , "y" , 1 , "number of ..." );
GENX( float , "z" , 6.3 , "this value sets ..." );
GENX( std::string , "name" , "myname" , "name of ..." );
然后,他可以在不同的地方与通常是不同的定义中定义它为每个#包括使用它:
class X
{
public :
void setDefaults()
{
#define GENX( type , member , value , help )\
member = value ;
#include "gen.x"
#undef GENX
}
void help( std::ostream & o )
{
#define GENX( type , member , value , help )\
o << #member << " : " << help << '\n' ;
#include "gen.x"
#undef GENX
}
private :
#define GENX( type , member , value , help )\
type member ;
#include "gen.x"
#undef GENX
}
您可以看看 Boost.Preprocessor 找到的预处理器的有趣的用途很多的...
SHOW() 用于调试:
#define SHOW(X) cout << # X " = " << (X) << endl
双重评估扩展参数技巧:(例如。使用实际行号而不是“__LINE__”。)
/* Use CONCATENATE_AGAIN to expand the arguments to CONCATENATE */
#define CONCATENATE( x,y) CONCATENATE_AGAIN(x,y)
#define CONCATENATE_AGAIN(x,y) x ## y
静态编译时断言。
例如。:
#define CONCATENATE_4( a,b,c,d) CONCATENATE_4_AGAIN(a,b,c,d)
#define CONCATENATE_4_AGAIN(a,b,c,d) a ## b ## c ## d
/* Creates a typedef that's legal/illegal depending on EXPRESSION. *
* Note that IDENTIFIER_TEXT is limited to "[a-zA-Z0-9_]*". *
* (This may be replaced by static_assert() in future revisions of C++.) */
#define STATIC_ASSERT( EXPRESSION, IDENTIFIER_TEXT) \
typedef char CONCATENATE_4( static_assert____, IDENTIFIER_TEXT, \
____failed_at_line____, __LINE__ ) \
[ (EXPRESSION) ? 1 : -1 ]
使用通过:
typedef int32_t int4;
STATIC_ASSERT( sizeof(int4) == 4, sizeof_int4_equal_4 );
初始化 CodeLocation 类的实例:(从调用点存储文件/行/函数——这*只能*通过宏或通过直接访问源点的 __FILE__/__LINE__/etc 宏来完成。)
/* Note: Windows may have __FUNCTION__. C99 defines __func__. */
#define CURRENT_CODE_LOCATION() \
CodeLocation( __PRETTY_FUNCTION__, __FILE__, __LINE__ )
随后被 MESSAGE/WARN/FAIL 宏用作方便的源位置打印机制。例如:
#define WARN_IF_NAN(X) \
do \
{ \
if ( isnan(X) != 0 ) \
WARN( # X " is NaN (Floating Point NOT-A-NUMBER)" ); \
if ( isinf(X) != 0 ) \
WARN( # X " is INF (Floating Point INFINITY)" ); \
} while ( false )
断言/除非宏。您可以通过宏传递任何标记,包括“==”等运算符。所以构造如下:
ASSERT( foo, ==, bar )
或者
UNLESS( foo, >=, 0, value=0; return false; );
是合法的。Assert/Unless 宏可以自动添加各种有用的信息,例如 CodeLocation、堆栈跟踪或抛出异常/核心转储/优雅退出。
使 errno 更简单:
#define ERRNO_FORMAT "errno= %d (\"%s\")"
#define ERRNO_ARGS errno, strerror(errno)
#define ERRNO_STREAM "errno= " << errno << " (\"" << strerror(errno) << "\") "
例如。printf("打开失败。“ ERRNO_FORMAT,ERRNO_ARGS );
我的一个惯用的手段是通过可变数量的参数,以宏,在调用类printf函数例如用于以后的一种方式。要做到这一点,我指定宏只有一个参数和宏的身体使用它,而(),但所有的参数传递给宏((和)),因此列表看起来像一个参数。例如,
#define TRACE( allargs) do { printf allargs; } while ( 0)
...
TRACE(( "%s %s\n", "Help", "me"));
日志记录是一个地方宏特别经常使用:
#define LOG(log) \
if (!log.enabled()) {} \
else log.getStream() << __FILE__ << "@" << __LINE__ << ": "
log_t errorlog;
...
LOG(errorlog) << "This doesn't look good:" << somedata;
我的信用肖恩·巴雷特对于这个有趣的一个:
#ifndef blah
#define blah(x) // something fun
#include __FILE__
#undef blah
#endif
#ifndef blah
#define blah(x) // something else that is also fun
#include __FILE__
#undef blah
#endif
#ifdef blah
blah(foo)
blah(bar)
#endif
你基于某些更高级别的结构,可以通过宏表示哈克的方式来获得预处理器生成代码。
我用宏的主要场所是在我自己的测试框架。例如,当欲断言一些代码必须抛出,我使用这个宏:
#define MUST_THROW( expr )
try {
(expr);
(myth_suite_).Fail( #expr +
std::string( " should throw but didn't" ) );
}
catch( ... ) {
}
和使用它是这样的:
MUST_THROW( some_bogus_stuff() );
MUST_THROW( more_bogus_stuff() );
我使用它们唯一的其他地方是在类声明。我有一个宏:
#define CANNOT_COPY( cls ) \
private: \
cls( const cls & ); \
void operator=( const cls & ) \
我使用来指定一个类不能被复制(或分配):
class BankAccount {
CANNOT_COPY( BankAccount );
....
};
这并没有做什么特别的,但吸引人们的关注,并可以很容易地被搜索。
有关嵌入的代码,从一个很好的特技 embeddedgurus.com 可以处理的二进制值:
B8(01010101) // 85
B16(10101010,01010101) // 43,605
B32(10000000,11111111,10101010,01010101) // 2,164,238,93
此实现类似的目标,从@Ferruccio约BOOST_BINARY之前的响应,虽然有点扩大。
下面是代码(copy'n粘贴,而不是测试,参见链接查看更多细节)
// Internal Macros
#define HEX__(n) 0x##n##LU
#define B8__(x) ((x&0x0000000FLU)?1:0) \
+((x&0x000000F0LU)?2:0) \
+((x&0x00000F00LU)?4:0) \
+((x&0x0000F000LU)?8:0) \
+((x&0x000F0000LU)?16:0) \
+((x&0x00F00000LU)?32:0) \
+((x&0x0F000000LU)?64:0) \
+((x&0xF0000000LU)?128:0)
// User-visible Macros
#define B8(d) ((unsigned char)B8__(HEX__(d)))
#define B16(dmsb,dlsb) (((unsigned short)B8(dmsb)<<8) + B8(dlsb))
#define B32(dmsb,db2,db3,dlsb) \
(((unsigned long)B8(dmsb)<<24) \
+ ((unsigned long)B8(db2)<<16) \
+ ((unsigned long)B8(db3)<<8) \
+ B8(dlsb))
我喜欢的宏。在调试的时候这么多的乐趣!
我经常包裹之类的东西调试声纳在一个简单的宏,允许它被编译出释放构建:
#ifdef DEBUG
#define D(s) do { s; } while(0)
#else
#define D(s) do {/**/} while(0)
#endif
使用后通常是这样的:
D(printf("level %d, condition %s\n", level, condition));
在do{}while(0)
成语是存在,以避免可能导致意外使D(...)
的使用条件或循环的唯一内容的问题。你不希望这样的代码意味着错误的事情,毕竟:
for(i=1;i<10;++i) D(printf("x[%d]=%f\n",i,x[i]));
SomeReallyExpensiveFunction(x);
如果我能有这样的情况下,抛出一个错误,我会,但预处理器必须是一个完整的编译器本身,以告诉D()
宏是一个循环体的唯一内容。
我也编译时断言一个大风扇。我的配方略有不同,但有超过别人我见过没有真正的优势。关键是要形成一个唯一命名的typedef如果断言条件为假抛出一个错误,而不是别的。在cassert.h我们有:
/*! \brief Compile-time assertion.
*
* Note that the cassert() macro generates no code, and hence need not
* be restricted to debug builds. It does have the side-effect of
* declaring a type name with typedef. For this reason, a unique
* number or string of legal identifier characters must be included
* with each invocation to avoid the attempt to redeclare a type.
*
* A failed assertion will attempt to define a type that is an array
* of -1 integers, which will throw an error in any standards
* compliant compiler. The exact error is implementation defined, but
* since the defined type name includes the string "ASSERTION" it
* should trigger curiosity enough to lead the user to the assertion
* itself.
*
* Because a typedef is used, cassert() may be used inside a function,
* class or struct definition as well as at file scope.
*/
#define cassert(x,i) typedef int ASSERTION_##i[(x)?1:-1]
和在一些源文件,任何地方一个typedef将是合法的:
#include "cassert.h"
...
cassert(sizeof(struct foo)==14, foo1);
...
将得到的错误消息常常是模糊的,但将包含标识符的片段使有问题的行被蛮力来发现。
我一直内疚的地方使用本预处理那里写一个代码生成工具可能是最佳答案,就像在另一个答案是产生大量的样板的基础上枚举成员的独特部分的代码名称。也就是说特别方便时编写大量消息分派胶的在C进行编译。
STRUCT文字用默认值(即不为零),使用C99可变参数宏
struct Example {
int from;
int to;
const char *name;
}
#define EXAMPLE(...) ((struct Example){.from=0, .to=INT_MAX, .name="", __VA_ARGS__})
使用EXAMPLE(.name="test")
使用默认值,除了name
的明确覆盖。此遮蔽与后提到的相同构件在标准中定义良好。
一个可以简化,即重复的事情。枚举列表
enum {
kOneEnum,
kTwoEnum,
kThreeEnum,
kFourEnum
};
...和后做一个开关壳体在结构化的方式
#define TEST( _v ) \
case k ## _v ## Enum: \
CallFunction ## _v(); \
break;
switch (c) {
TEST( One );
TEST( Two );
TEST( Three );
TEST( Four );
}
注:的肯定,这可以用一个函数指针数组做,但这个打开多一点灵活性添加参数,并且还与单个哈希使用字符串扩展
...或测试对字符串以得到正确的枚举值
int value = -1;
char *str = getstr();
#define TEST( _v ) \
if (!strcmp(# _v, str)) \
value = k ## _v ## Enum
TEST( One );
TEST( Two );
TEST( Three );
TEST( Four );
您可以使用宏来定义具有不同数据类型的相同功能。例如:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define DEFINE_BITS_STR(name, type) \
char *bits_str_##name(type value) \
{ \
int len = sizeof(type) * CHAR_BIT; \
char *result; \
type n; \
int i; \
\
result = (char *)calloc(len+1, sizeof(type)); \
if(result == NULL) \
return NULL; \
\
memset(result, '0', len); \
result[len] = 0x00; \
\
n = value; \
i = len; \
while(n) \
{ \
if(n & 1) \
result[i] = '1'; \
\
n >>= 1; \
--i; \
} \
\
return result; \
}
DEFINE_BITS_STR(uchar, unsigned char)
DEFINE_BITS_STR(uint, unsigned int)
DEFINE_BITS_STR(int, unsigned int)
int main()
{
unsigned char value1 = 134;
unsigned int value2 = 232899;
int value3 = 255;
char *ret;
ret = bits_str_uchar(value1);
printf("%d: %s\n", value1, ret);
ret = bits_str_uint(value2);
printf("%d: %s\n", value2, ret);
ret = bits_str_int(value3);
printf("%d: %s\n", value3, ret);
return 1;
}
在此示例中定义了三个函数(bits_str_uchar()
, bits_str_uint()
, bits_str_int()
)处理三种不同的数据类型(unsigned char
, unsigned int
, int
)。但是,所有这些都返回一个包含所传递值的位的字符串。
当你实现一个COM服务器,你必须照顾所有异常的代码会可能抛出的 - 通过COM法边界,让一个异常会经常崩溃调用应用程序
方法托架是此是有用的。有一个开口托架其为含有“尝试”宏并包含了一组“捕获” ES,异常转换成ERRORINFO的包装和生产的HRESULT一个右括号。
从CrashRpt项目,需要特技加宽宏和定义:
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
std::wstring BuildDate = std::wstring(WIDEN(__DATE__)) + L" " + WIDEN(__TIME__);
大多数(所有?)C ++单元测试框架是基于宏建。我们使用单元测试++ 。检查出来,看看各种花哨的宏。
在 BOOST_BINARY 宏执行一些clevel预处理器诡计,得到C ++表示中二进制数字常数的能力。它仅限于然而0-255。
在并行线程工具宏是particularily可观IMHO。
当我在巨大的C / C ++嵌套结构工作像用于3GPP RRC / NBAP / RNSAP一个,我遵循这一招使代码看起来干净。
struct leve1_1
{
int data;
struct level2
{
int data;
struct level3
{
int data;
} level_3_data;
} level_2_data;
} level_1_data;
level_1_data.data = 100;
#define LEVEL_2 leve1_1_data.level_2_data
LEVEL_2.data = 200;
#define LEVEL_3 LEVEL_2.level_3_data
LEVEL_3.data = 300;
#undef LEVEL_2
#undef LEVEL_3
这会使生活更容易在设计时和代码维护time..also期间将是可读的。
将它们转换为改善安全型和调试能力的语言的构建体。
void _zero_or_die(int v, const char* filename, int line)
{
if (v != 0)
{
fprintf(stderr, "error %s:%d\n", filename, line);
exit(1);
}
}
#define ZERO_OR_DIE_ for (int _i=1; _i == 1; _zero_or_die(_i, __FILE__, __LINE__)) _i=
ZERO_OR_DIE_ pipe(fd);
ZERO_OR_DIE_ close(0);
ZERO_OR_DIE_ sigaction(SIGSEGV, &sigact, NULL);
ZERO_OR_DIE_ pthread_mutex_lock(&mt);
ZERO_OR_DIE_ pthread_create(&pt, NULL, func, NULL);
在微控制器中,通常使用UART调试代码,硬件断点具有许多缺点。
这是已被证明是非常有用的一个简单的宏:
#define DEBUG_OUT(value) sprintf(uartTxBuf, "%s = 0x%04X\n", #value, value);\
puts_UART((uint16_t *) uartTxBuf)
用例:
for (i=0; i < 4; i++)
{
DEBUG_OUT(i);
DEBUG_OUT(i % 3);
}
:收到流:
i = 0x0000
i % 3 = 0x0000
i = 0x0001
i % 3 = 0x0001
i = 0x0002
i % 3 = 0x0002
i = 0x0003
i % 3 = 0x0000
是,这是粗和不安全的。这只是应用,直到错误被隔离,所以这个宏没有任何伤害。
我经常使用它。我有一个debug.h
头定义如下所示:
#ifndef DEBUG_H
#define DEBUG_H
#ifdef DEBUG
#define debuf if(1)
#else
#define debug if(0)
#endif
#endif
和然后:
debug {
printf("message from debug!");
}
如果你想获得"message from debug!"
消息,编译:
gcc -D DEBUG foo.c
否则,没有任何反应。 GCC是一个非常聪明的编译器。如果没有定义DEBUG
,所产生的if(0)
(死代码)将从与一些优化代码被删除。
您还可以做得更多:
debug
{
pritnf("I'm in debug mode!\n");
}
else
{
printf("I'm not in debug mode\n");
}
若干天前,我看到的 d编程语言提供非常相似的功能了。
如果你认为以上没有上下文,则可以定义为认为
#define in_debug if(1)
#define not_debug else
然后
in_debug {
printf("I'm in debug mode!");
}
not_debug {
printf("Not in debug mode!");
}
在宏,它很容易为做控制流程,因为它只是文本替换。下面是一个for循环的示例:
#include <stdio.h>
#define loop(i,x) for(i=0; i<x; i++)
int main(int argc, char *argv[])
{
int i;
int x = 5;
loop(i, x)
{
printf("%d", i); // Output: 01234
}
return 0;
}