(Originally published on reddit, archived here in lightly edited form for posterity.)
A recent (now deleted) discussion thread aroused some rather strong emotions w.r.t. how a key library embedded in a product used by many millions of folks reported errors via fprintf(stderr,...)
. (It turned out to be a false alarm: the stderr logging lines were for various command-line utilities and example code, and none of it was linked into the actual library.)
As a rule of thumb, general-use libraries should NOT do this, for reasons ranging to “stderr may have been inadvertently closed” to “that might itself cause further errors”. The only exception: logging libraries. (D’oh!)
Instead, define an enum
to properly scope the range of error codes you return with each function; that should cover 99% of your needs. If your users need more details, provide a function in the spirit of strerror(3) for callers to retrieve them.
There are certainly more complicated ways to handle errors, but the above should cover all but the most esoteric circumstances.