Showing posts with label attribute. Show all posts
Showing posts with label attribute. Show all posts

Monday, June 13, 2011

'warn_unused_result' attribute in gcc

If you want to enforce checking return value of your function you can specify warn_unused_result attribute in your function declaration (ofcourse attributes can be placed only in declarations not definitions). If this attibute is specified and caller does not check the return value, the compiler outputs warning message for not checking return value. This does not mean you need to check the return value but bare assignment also removes this warning. Ofcourse it is difficult as well as ugly to check against condition. Warning is well sufficient. Here is an example. Using this attribute in void function has no effect. gcc simply ignores the attribute and same is displayed in compilation output.

int check() __attribute__((warn_unused_result));
int check()
{
return 0;
}

int main()
{
check();
/*
compiler warns of not checking return value --
warning: ignoring return value of check,
declared with attribute warn_unused_result
*/

int k = check();//no warning
}

Thursday, June 9, 2011

'weak' attribute in gcc

Recently I came to know about gcc attributes which can be used in code for specific purpose. One of them I understood early was 'weak' attribute. A 'weak' attribute may be specified if you don want compiler to throw any error if it was unable to resolve external symbols. This is useful if you are planning to provide function or variable in near future and do not want to modify the main source at that time.

#include<stdio.h>

extern int k() __attribute__((weak));
extern int k2 __attribute__((weak));

int main()
{
if(k == NULL)
{
if(&k2 == NULL)
{
printf("No symbol k or k2 found\n");
}
}
else
{
k();
}
}

This example compiles just fine and gives no linkage error even if the symbols are not found. However if we are using those symbols we need to check NULLness of those symbols else the program will result in seg fault.