Static assert in C

前端 未结 12 767
感情败类
感情败类 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 17:12

    If using the STATIC_ASSERT() macro with __LINE__, it is possible to avoid line number clashes between an entry in a .c file and a different entry in a header file by including __INCLUDE_LEVEL__.

    For example :

    /* Trickery to create a unique variable name */
    #define BOOST_JOIN( X, Y )      BOOST_DO_JOIN( X, Y )
    #define BOOST_DO_JOIN( X, Y )   BOOST_DO_JOIN2( X, Y )
    #define BOOST_DO_JOIN2( X, Y )  X##Y
    #define STATIC_ASSERT(x)        typedef char \
            BOOST_JOIN( BOOST_JOIN(level_,__INCLUDE_LEVEL__), \
                        BOOST_JOIN(_assert_on_line_,__LINE__) ) [(x) ? 1 : -1]
    

提交回复
热议问题