在构build时在C中ASSERTexpression式的方法

我正在整理一些在整个地方使用“神奇数字”来设置硬件寄存器的旧代码,我想用常数而不是这些数字来使代码更具performance力(实际上它们将映射到名称/用来logging寄存器的值)。

不过,我担心随着变化量的增加,我可能会打破魔法数字。 这是一个简单的例子(寄存器组更复杂):

const short mode0 = 0; const short mode1 = 1; const short mode2 = 2; const short state0 = 0; const short state1 = 4; const short state2 = 8; 

所以不是:

 set_register(5); 

我们有:

 set_register(state1|mode1); 

我正在寻找的是一个构build时间版本:

 ASSERT(5==(state1|mode1)); 

更新

@Christian,感谢您的快速响应,我也对C / non-boost环境的答案感兴趣,因为这是驱动程序/内核代码。

新答案

在我原来的回答(下面)中,我必须有两个不同的macros来支持函数范围和全局范围的断言。 我想知道是否有可能提出一个解决scheme,可以在两个范围内工作。

我能find一个适用于Visual Studio和Comeau编译器的解决scheme,使用extern字符数组。 但是我能find一个适用于GCC的更复杂的解决scheme。 但GCC的解决scheme不适用于Visual Studio。 :(但添加一个'#ifdef __ GNUC __',很容易为给定的编译器select正确的macros集合。

解:

 #ifdef __GNUC__ #define STATIC_ASSERT_HELPER(expr, msg) \ (!!sizeof \ (struct { unsigned int STATIC_ASSERTION__##msg: (expr) ? 1 : -1; })) #define STATIC_ASSERT(expr, msg) \ extern int (*assert_function__(void)) [STATIC_ASSERT_HELPER(expr, msg)] #else #define STATIC_ASSERT(expr, msg) \ extern char STATIC_ASSERTION__##msg[1]; \ extern char STATIC_ASSERTION__##msg[(expr)?1:2] #endif /* #ifdef __GNUC__ */ 

这里是STATIC_ASSERT(1==1, test_message);报告的错误信息STATIC_ASSERT(1==1, test_message); 在test.c的第22行:

GCC:

 line 22: error: negative width in bit-field `STATIC_ASSERTION__test_message' 

视觉工作室:

 test.c(22) : error C2369: 'STATIC_ASSERTION__test_message' : redefinition; different subscripts test.c(22) : see declaration of 'STATIC_ASSERTION__test_message' 

科莫:

 line 22: error: declaration is incompatible with "char STATIC_ASSERTION__test_message[1]" (declared at line 22) 

原文答案

我做了一些与跳棋非常相似的东西。 但是,我在很多编译器中都会显示一条消息:

 #define STATIC_ASSERT(expr, msg) \ { \ char STATIC_ASSERTION__##msg[(expr)?1:-1]; \ (void)STATIC_ASSERTION__##msg[0]; \ } 

而在全球范围内(function之外)做一些事情可以使用这个:

 #define GLOBAL_STATIC_ASSERT(expr, msg) \ extern char STATIC_ASSERTION__##msg[1]; \ extern char STATIC_ASSERTION__##msg[(expr)?1:2] 

Ralf Holly的一篇文章研究了C中静态断言的不同选项

他提出了三种不同的方法:

  • 开关情况值必须是唯一的
  • 数组不能有负面的尺寸
  • 常量expression式除以零

他最好的实施结论是:

 #define assert_static(e) \ do { \ enum { assert_static__ = 1/(e) }; \ } while (0) 

检出boost的静态断言

如果你没有访问第三方库的静态断言函数(如boost),你可以推出自己的静态断言:

 #define STATIC_ASSERT(x) \ do { \ const static char dummy[(x)?1:-1] = {0};\ } while(0) 

当然,缺点是错误信息不会很有帮助,但至less会给你一个行号。

 #define static_assert(expr) \ int __static_assert(int static_assert_failed[(expr)?1:-1]) 

它可以随时随地使用。 我认为这是最简单的解决scheme。

在使用之前,请仔细用您的编译器进行testing。

这里列出的任何技术都可以工作,当C ++ 0x变得可用时,您将能够使用内置的static_assert关键字。

如果你有Boost,那么使用BOOST_STATIC_ASSERT是最好的select。 如果你正在使用C或不想获得Boost,那么这里是我的c_assert.h文件,它定义了一些处理静态断言的macros(并解释了这些macros的工作原理)。

有一点更复杂,因为在ANSI C代码中,需要2个不同的macros – 一个可以在你有声明的区域工作,另一个可以在正常声明的区域工作。 还有一点工作要在全球范围内或在范围内进行macros观工作,以及确保没有名称冲突的一堆垃圾。

STATIC_ASSERT()可以在variables声明块或全局范围中使用。

STATIC_ASSERT_EX()可以在常规语句中。

对于C ++代码(或允许声明与语句混合的C99代码), STATIC_ASSERT()将在任何地方工作。

 /* Define macros to allow compile-time assertions. If the expression is false, an error something like test.c(9) : error XXXXX: negative subscript will be issued (the exact error and its format is dependent on the compiler). The techique used for C is to declare an extern (which can be used in file or block scope) array with a size of 1 if the expr is TRUE and a size of -1 if the expr is false (which will result in a compiler error). A counter or line number is appended to the name to help make it unique. Note that this is not a foolproof technique, but compilers are supposed to accept multiple identical extern declarations anyway. This technique doesn't work in all cases for C++ because extern declarations are not permitted inside classes. To get a CPP_ASSERT(), there is an implementation of something similar to Boost's BOOST_STATIC_ASSERT(). Boost's approach uses template specialization; when expr evaluates to 1, a typedef for the type ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed<true>) > which boils down to ::interslice::StaticAssert_test< 1> which boils down to struct StaticAssert_test is declared. If expr is 0, the compiler will be unable to find a specialization for ::interslice::StaticAssert_failed<false>. STATIC_ASSERT() or C_ASSERT should work in either C or C++ code (and they do the same thing) CPP_ASSERT is defined only for C++ code. Since declarations can only occur at file scope or at the start of a block in standard C, the C_ASSERT() or STATIC_ASSERT() macros will only work there. For situations where you want to perform compile-time asserts elsewhere, use C_ASSERT_EX() or STATIC_ASSERT_X() which wrap an enum declaration inside it's own block. */ #ifndef C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546 #define C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546 /* first some utility macros to paste a line number or counter to the end of an identifier * this will let us have some chance of generating names that are unique * there may be problems if a static assert ends up on the same line number in different headers * to avoid that problem in C++ use namespaces */ #if !defined( PASTE) #define PASTE2( x, y) x##y #define PASTE( x, y) PASTE2( x, y) #endif /* PASTE */ #if !defined( PASTE_LINE) #define PASTE_LINE( x) PASTE( x, __LINE__) #endif /* PASTE_LINE */ #if!defined( PASTE_COUNTER) #if (_MSC_VER >= 1300) /* __COUNTER__ introduced in VS 7 (VS.NET 2002) */ #define PASTE_COUNTER( x) PASTE( x, __COUNTER__) /* __COUNTER__ is a an _MSC_VER >= 1300 non-Ansi extension */ #else #define PASTE_COUNTER( x) PASTE( x, __LINE__) /* since there's no __COUNTER__ use __LINE__ as a more or less reasonable substitute */ #endif #endif /* PASTE_COUNTER */ #if __cplusplus extern "C++" { // required in case we're included inside an extern "C" block namespace interslice { template<bool b> struct StaticAssert_failed; template<> struct StaticAssert_failed<true> { enum {val = 1 }; }; template<int x> struct StaticAssert_test { }; } } #define CPP_ASSERT( expr) typedef ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed< (bool) (expr) >) > PASTE_COUNTER( IntersliceStaticAssertType_) #define STATIC_ASSERT( expr) CPP_ASSERT( expr) #define STATIC_ASSERT_EX( expr) CPP_ASSERT( expr) #else #define C_ASSERT_STORAGE_CLASS extern /* change to typedef might be needed for some compilers? */ #define C_ASSERT_GUID 4964f7ac50fa4661a1377e4c17509495 /* used to make sure our extern name doesn't collide with something else */ #define STATIC_ASSERT( expr) C_ASSERT_STORAGE_CLASS char PASTE( PASTE( c_assert_, C_ASSERT_GUID), [(expr) ? 1 : -1]) #define STATIC_ASSERT_EX(expr) do { enum { c_assert__ = 1/((expr) ? 1 : 0) }; } while (0) #endif /* __cplusplus */ #if !defined( C_ASSERT) /* C_ASSERT() might be defined by winnt.h */ #define C_ASSERT( expr) STATIC_ASSERT( expr) #endif /* !defined( C_ASSERT) */ #define C_ASSERT_EX( expr) STATIC_ASSERT_EX( expr) #ifdef TEST_IMPLEMENTATION C_ASSERT( 1 < 2); C_ASSERT( 1 < 2); int main( ) { C_ASSERT( 1 < 2); C_ASSERT( 1 < 2); int x; x = 1 + 4; C_ASSERT_EX( 1 < 2); C_ASSERT_EX( 1 < 2); return( 0); } #endif /* TEST_IMPLEMENTATION */ #endif /* C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546 */ 

尝试:

 #define STATIC_ASSERT(x, error) \ do { \ static const char error[(x)?1:-1];\ } while(0) 

那么你可以写:

 STATIC_ASSERT(a == b, a_not_equal_to_b); 

这可能会给你一个更好的错误信息(取决于你的编译器)。

Alexandrescu的“ 现代C ++devise” (ISBN 978-0201704310)也对STATIC_ASSERT技术进行了非常全面的考察。

常见的便携式选项是

 #if 5 != (state1|mode1) # error "aaugh!" #endif 

但在这种情况下它不起作用,因为它们是C常量而不是#define

你可以看到Linux内核的BUILD_BUG_ONmacros来处理你的情况:

 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)])) 

condition为真时,这成为((void)sizeof(char[-1])) ,这是非法的,应该在编译时失败,否则就变成((void)sizeof(char[1]))正好。