[小技巧] gcc attribute error 属性小试

gcc __attribute__  里有一个属性是 error 能够用于编译时报错。


參考:

https://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html

error (" message ") If this attribute is used on a function declaration and a call to such a functionis not eliminated through dead code elimination or other optimizations, an errorwhich will include message will be diagnosed. This is usefulfor compile time checking, especially together with __builtin_constant_pand inline functions where checking the inline function arguments is notpossible through extern 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 presence of 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这个属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值