gcc __attribute__ 里有一个属性是 error 能够用于编译时报错。
參考:
https://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html
error ("
message")
will include message will be diagnosed. This is usefulfor compile time checking, especially together with
__builtin_constant_p
and inline functions where checking the inline function arguments is notpossible throughextern char [(condition) ? 1 : -1];
tricks. While it is possible to leave the function undefined and thus invokea link failure, when using this attribute the problem will be diagnosedearlier and with exact location of the call even in presenceof inlinefunctions or when not emitting debugging information.
写了一个简单的演示样例:
extern void foo(void) __attribute__((error("build failed"))); #define FOO 0 int main(void) { if(FOO == 0) foo(); return 1; }
这里因为 FOO == 0 推断成立,所以会在编译时候直接报以下的错误:
/tmp/helloworld.c: In function ‘main‘:
/tmp/helloworld.c:7:6: error: call to ‘foo‘ declared with attribute error: build failed
这里文件名称/行号和错误的信息 "build failed" 都会输出。
另外。内核的 BUILD_BUG() 这个宏也是用了GCC这个属性。
时间: 2025-01-04 07:12:29