Reputation: 26671
I don't always use all return values, and sometimes I must handle return values. For instance:
$ make
gcc -pedantic -std=c99 -Wall -O3 -ledit -g -DVERSION=\"v0.160425-2-gc443\" -c -o main.o main.c
main.c: In function ‘int_handler’:
main.c:532:5: warning: ignoring return value of ‘write’, declared with attribute warn_unused_result [-Wunused-result]
write(fileno(stdin), s, sizeof s - 1);
^
gcc -o shell main.o errors.c util.c pipeline.c -ledit
What should I do to avoid the warning? Is there a good way to "use" a variable like writing it to /dev/null
so that the compiler won't complain? My own idea is this, which deals with the problem without ignoring the error and I can commit my code without warnings and deal with this later:
void int_handler(int signum) {
if (write(fileno(stdin), s, sizeof s - 1)) {
} else {}
}
Upvotes: 1
Views: 271
Reputation: 29
The prototype for write in the header file unistd.h has been declared as follows
extern ssize_t write (int __fd, const void *__buf, size_t __n) __wur
and __wur has been defined as (in cdefs.h)
# if __USE_FORTIFY_LEVEL > 0
# define __wur __attribute_warn_unused_result__
# endif
#else
# define __attribute_warn_unused_result__ /* empty */
So when you are compiling with fortify switch on, wur gets defined as __attribute_warn_unused_result. This attribute essentially tells the compiler to throw out warning if return value of function is not used.
You can redirect your stdout and stderr to /dev/null
gcc -c file.c > /dev/null 2>&1
and get rid of the warning (though even error is redirected to null) or you can redirect to file as
gcc -c warn.c > xx 2>&1
Hope this helps . And like said above, always check the value of "write", the error will automatically vanish :)
Upvotes: 1
Reputation: 36441
It is a bad idea to not take in account the return value of a call to write
, as an I/O may fail it is important to take care of such an event. If you really want to remove the warning, you should explicitly ignore the return value:
(void)write(...);
Upvotes: 2
Reputation: 214890
First of all, in case of file handling functions in production-quality code, you should almost certainly handle all return values.
Otherwise, the standard way to ignore a variable or a function result, is to cast it to (void)
.
Upvotes: 2
Reputation: 121427
Typically to suppress this warning, you can do:
(void)write(fileno(stdin), s, sizeof s - 1);
But the reason for the warning is because write()
is declared with an attribute in the header (<unistd.h>
) which leads to the warning.
This (attribute) is not done for every function but selectively. For example, printf()
's return is typically ignored.
Since, you would want to check the results of IO operation, it's done for write()
.
So, if you really want to ignore the result, you can use the (void)func(...);
to suppress this.
Upvotes: 3