码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-24 10:42:58      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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这个属性。

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/robertsong2004/article/details/47036431

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!