Static assert in C

前端 未结 12 713
感情败类
感情败类 2020-11-22 16:22

What\'s the best way to achieve compile time static asserts in C (not C++), with particular emphasis on GCC?

12条回答
  •  难免孤独
    2020-11-22 16:51

    cl

    I know the question explicitly mentions gcc, but just for completeness here is a tweak for Microsoft compilers.

    Using the negatively sized array typedef does not persuade cl to spit out a decent error. It just says error C2118: negative subscript. A zero-width bitfield fares better in this respect. Since this involves typedeffing a struct, we really need to use unique type names. __LINE__ does not cut the mustard — it is possible to have a COMPILE_TIME_ASSERT() on the same line in a header and a source file, and your compile will break. __COUNTER__ comes to the rescue (and it has been in gcc since 4.3).

    #define CTASTR2(pre,post) pre ## post
    #define CTASTR(pre,post) CTASTR2(pre,post)
    #define STATIC_ASSERT(cond,msg) \
        typedef struct { int CTASTR(static_assertion_failed_,msg) : !!(cond); } \
            CTASTR(static_assertion_failed_,__COUNTER__)
    

    Now

    STATIC_ASSERT(sizeof(long)==7, use_another_compiler_luke)
    

    under cl gives:

    error C2149: 'static_assertion_failed_use_another_compiler_luke' : named bit field cannot have zero width

    Gcc also gives an intelligible message:

    error: zero width for bit-field ‘static_assertion_failed_use_another_compiler_luke’

提交回复
热议问题