C language implements compile-time assertion

Compile-time assertion is a kind of assertion on the value of constants that can be calculated at compile time, so as to avoid introducing some unreasonable values ​​in the code.

Realization principle

The assertion at compile time is to take advantage of the feature that the compiler will report an error when it encounters the __error__ attribute when compiling and linking. We write a macro to extern a function that does not exist when the check condition fails at compile time, and specify the information to be output when the function compiles and reports an error. In this case, once the compile-time check condition fails, the compiler will find that our code externs a function that does not exist and has the __error__ attribute, so the compiler will report an error and stop compiling. This is the main principle.

When compile-time checks pass, the compiler discards code for paths that are not called. That is to say, the code that we deliberately created to throw errors will be lost.

So, if the condition asserted at compile time cannot be calculated at compile time, what should we do? Since our condition cannot be calculated at compile time, the above macro will be compiled into the code, and the compiler will also encounter the __error__ attribute, so the compilation will also be terminated.

Implementation in Dragonos

In the commit 9b37ff3e , DragonOS added the code of compile-time assertion.

Please indicate the source of the reprint: C language implements compile-time assertions | | Longjin's blog

Guess you like

Origin blog.csdn.net/qq_34026204/article/details/127184349
Recommended