25

我正在整理一些旧代码,这些代码到处使用“幻数”来设置硬件寄存器,我想使用常量而不是这些数字来使代码更具表现力(实际上它们会映射到名称/values 用于记录寄存器)。

然而,我担心随着变化的数量,我可能会打破神奇的数字。这是一个简化的示例(寄存器集更复杂):

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);

我正在寻找的是构建时版本:

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

更新

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

4

11 回答 11

27

新答案

在我的原始答案(如下)中,我必须有两个不同的宏来支持函数范围和全局范围内的断言。我想知道是否有可能提出一个适用于两种范围的单一解决方案。

我能够使用外部字符数组找到适用于 Visual Studio 和 Comeau 编译器的解决方案。但我能够找到适用于 GCC 的更复杂的解决方案。但是 GCC 的解决方案不适用于 Visual Studio。:( 但是添加一个'#ifdef __ GNUC __',很容易为给定的编译器选择正确的宏集。

解决方案:

#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);以下是test.c 第 22 行报告的错误消息:

海合会:

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)

 
 

原始答案

我做的事情与 Checkers 所做的非常相似。但我包含一条消息,该消息会出现在许多编译器中:

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

对于在全局范围内(函数外)做某事,请使用:

#define GLOBAL_STATIC_ASSERT(expr, msg)   \
  extern char STATIC_ASSERTION__##msg[1]; \
  extern char STATIC_ASSERTION__##msg[(expr)?1:2]
于 2008-10-06T14:15:32.360 回答
15

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

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

  • switch case 值必须是唯一的
  • 数组不能有负维度
  • 常量表达式除以零

他对最佳实施的结论是:

#define assert_static(e) \
    do { \
        enum { assert_static__ = 1/(e) }; \
    } while (0)
于 2008-12-02T13:01:35.467 回答
11

Checkout boost 的静态断言

于 2008-10-06T13:50:31.240 回答
11

如果您无权访问第三方库静态断言函数(如 boost),则可以滚动自己的静态断言:

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

当然,缺点是该错误消息不会很有帮助,但至少它会为您提供行号。

于 2008-10-06T13:55:12.807 回答
8
#define static_assert(expr) \
int __static_assert(int static_assert_failed[(expr)?1:-1])

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

在使用之前,请使用您的编译器仔细测试它。

于 2011-05-22T10:46:40.857 回答
6

此处列出的任何技术都应该有效,当 C++0x 可用时,您将能够使用内置static_assert关键字。

于 2008-10-06T15:24:11.580 回答
5

尝试:

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

然后你可以写:

STATIC_ASSERT(a == b, a_not_equal_to_b);

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

于 2008-10-06T14:09:18.893 回答
5

如果你有 Boost,那么使用BOOST_STATIC_ASSERT是要走的路。如果您使用 C 或不想获得 Boost,这是我的c_assert.h文件,它定义(并解释了其工作原理)一些宏来处理静态断言。

应该是有点复杂,因为在 ANSI C 代码中,您需要 2 个不同的宏 - 一个可以在您有声明的区域工作,另一个可以在正常语句所在的区域工作。还有一些工作可以使宏在全局范围或块范围内工作,还有一堆垃圾来确保没有名称冲突。

STATIC_ASSERT()可以在变量声明块或全局范围内使用。

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 */
于 2008-10-06T17:04:31.270 回答
3

常见的便携式选项是

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

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

您可以查看BUILD_BUG_ON处理您的情况的 Linux 内核宏:

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

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

于 2008-10-06T14:04:11.790 回答
1

确保使用足够新的编译器进行编译(例如gcc -std=c11)。

那么你的陈述很简单:

_Static_assert(state1|mode1 == 5, "Unexpected change of bitflags");
于 2018-04-26T15:55:46.953 回答
1
#define MODE0 0
#define MODE1 1
#define MODE2 2

#define STATE0 0
#define STATE1 4
#define STATE2 8

set_register(STATE1|STATE1); //set_register(5);
#if (!(5==(STATE1|STATE1))) //MY_ASSERT(5==(state1|mode1)); note the !
#error "error blah blah"
#endif

这不像单行 MY_ASSERT(expr) 解决方案那样优雅。您可以在编译 C 代码之前使用 sed、awk 或 m4 宏处理器来生成 MY_ASSERT(expr) 到多行的 DEBUG 代码扩展或将它们删除以用于生产的 NODEBUG 代码。

于 2020-06-15T18:41:04.433 回答