Static assert in C

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

    This works, with "remove unused" option set. I may use one global function to check global parameters.

    //
    #ifndef __sassert_h__
    #define __sassert_h__
    
    #define _cat(x, y) x##y
    
    #define _sassert(exp, ln) \
    extern void _cat(ASSERT_WARNING_, ln)(void); \
    if(!(exp)) \
    { \
        _cat(ASSERT_WARNING_, ln)(); \
    }
    
    #define sassert(exp) _sassert(exp, __LINE__)
    
    #endif //__sassert_h__
    
    //-----------------------------------------
    static bool tab_req_set_relay(char *p_packet)
    {
        sassert(TXB_TX_PKT_SIZE < 3000000);
        sassert(TXB_TX_PKT_SIZE >= 3000000);
        ...
    }
    
    //-----------------------------------------
    Building target: ntank_app.elf
    Invoking: Cross ARM C Linker
    arm-none-eabi-gcc ...
    ../Sources/host_if/tab_if.c:637: undefined reference to `ASSERT_WARNING_637'
    collect2: error: ld returned 1 exit status
    make: *** [ntank_app.elf] Error 1
    //
    

提交回复
热议问题