3

I got this error when compiling my programm in C.

warning: ignoring return value of ‘write’, declared with attribute warn_unused_result [-Wunused-result]

On all my call to write.

FLAGS : -g -Wall -Werror -Wextra -g -O2 // or -Ofast (same result)

GCC Version: 5.4

It happends when I'm trying to compile with -O2 or -Ofast.

Someone can explain me, why that's not working?

Thanks :)

pierreafranck
  • 445
  • 5
  • 19
  • 3
    It's a friendly compiler warning that you are not error checking `write(2)` call - it thinks you might be interested in knowing I/O failure. – P.P Feb 08 '18 at 14:04
  • 1
    It would appear that you are ignoring the return value of `write`. [man write](https://linux.die.net/man/2/write). – Lundin Feb 08 '18 at 14:09
  • 1
    Possible duplicate of [Warning: ignoring return value of 'scanf', declared with attribute warn\_unused\_result](https://stackoverflow.com/questions/7271939/warning-ignoring-return-value-of-scanf-declared-with-attribute-warn-unused-r) – Emil Laine Feb 08 '18 at 14:34

1 Answers1

9

Well, it is "working" but the compiler thinks you're missing something since you ignore the return value so it's giving you a warning. Not an error, although you're using -Werror so it will consider the warning an error and fail.

There are two solutions:

  1. Add code that checks the return value, and handles any errors; OR
  2. Cast the call to (void), thereby explicitly saying "this return value is here but I'm not using it".

Since I/O is brittle and can fail, the first is of course generally the best approach.

unwind
  • 391,730
  • 64
  • 469
  • 606