【问题标题】:Ways to ASSERT expressions at build time in C在 C 中构建时断言表达式的方法
【发布时间】:2010-09-15 12:27:03
【问题描述】:

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

但是,我担心更改量可能会打破神奇的数字。这是一个简化的例子(寄存器集更复杂):

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 / 非增强环境的答案感兴趣,因为这是驱动程序/内核代码。

【问题讨论】:

  • Alexandrescu 的Modern C++ Design,ISBN 978-0201704310 中也对 STATIC_ASSERT 技术进行了非常彻底的检查。

标签: c refactoring assert static-assert


【解决方案1】:

结帐提升的static assert

【讨论】:

  • 我在整个代码中都使用了这个。它甚至发现人们做了一些愚蠢的事情,这些事情会导致一两次无法解释但重大的破坏。
【解决方案2】:

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

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

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

【讨论】:

  • 很好的即兴创作,谢谢!在我的构建环境中,我遇到了错误:错误:#257: const variable "dummy" requires an initializer 所以我将其更改为 const static char dummy[(x)?1:-1]={0};如果您同意/更新此内容,我会将其标记为已回答,再次感谢。
【解决方案3】:

常见的便携选项是

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

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

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

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

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

【讨论】:

【解决方案4】:

试试:

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

然后你可以写:

STATIC_ASSERT(a == b, a_not_equal_to_b);

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

【讨论】:

  • 啊……你也打败了我吧! :-)
【解决方案5】:

新答案

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

我找到了一个适用于使用外部字符数组的 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__ */

以下是在 test.c 的第 22 行为 STATIC_ASSERT(1==1, test_message); 报告的错误消息:

GCC:

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

Visual Studio:

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]

【讨论】:

  • 我喜欢你对 msg 参数所做的事情;我可能必须将这种能力添加到我的。我还必须在 gcc 上测试我的。我想知道您是否在条件字符数组声明中将“2”更改为“-1”,这不会导致 gcc 出错吗?然后你就可以摆脱 gcc 的特殊情况了。
  • 由于您的宏与所要求的内容没有 100% 对应,因此您应该添加一些示例。您的解决方案需要 2 个参数,而第二个参数不是字符串。
【解决方案6】:

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

【讨论】:

  • C 不是 C++
【解决方案7】:

如果您有 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 */

【讨论】:

  • 为什么需要 PASTE 和 PASTE2 定义?不能直接用x##__LINE__或者x##__COUNTER__吗?
  • @Cœur:必须正确处理粘贴宏值。见stackoverflow.com/a/217181/12711
  • 感谢链接,部分解释。但是,仅当您直接在代码中使用 PASTE 宏时,才需要双重间接。由于PASTE 只在其他宏(PASTE_COUNTERPASTE_LINESTATIC_ASSERT)中有意义,所以第二级间接PASTE2 似乎没用。
  • 如果是直接调用的宏,FOO(x)使用带有操作数x的标记粘贴操作符,并以宏作为参数调用,那么粘贴的是宏名,而不是宏的值。这通常不是我们想要的。额外的间接性解决了这个问题。
【解决方案8】:

有一篇文章 Ralf Holly 检查 C 中静态断言的不同选项。

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

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

他对最佳实施的结论是:

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

【讨论】:

  • “do {... } while(0)”允许该宏仅在函数内工作。如果您在函数外部测试文件顶部的声明,编译器将发出错误。我将其简化为“enum { assert_static__ = 1/(e) }”,现在它可以在任何地方使用。
  • "assert_static__" ... 提示:将该虚拟变量称为提示错误的东西,例如:array_size_is_wrong
【解决方案9】:
#define static_assert(expr) \
int __static_assert(int static_assert_failed[(expr)?1:-1])

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

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

【讨论】:

  • 我喜欢它,尽管对于我正在进行的项目它不会这样做,因为我的编译器设置会抱怨一个声明但未使用的函数。
  • @AndyLester:这就是inline 关键字的用途,或者__attribute__((unused))
  • 不要在你自己的标识符中写双下划线——这些名字是为实现保留的,用于任何目的!
【解决方案10】:

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

那么你的陈述很简单:

_Static_assert(state1|mode1 == 5, "Unexpected change of bitflags");

【讨论】:

    【解决方案11】:
    #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 代码,将它们删除以用于生产。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2017-08-09
      • 2018-09-17
      • 1970-01-01
      相关资源
      最近更新 更多