14

I'm writing a C library for a software project. I need to do some error reporting, but I'm a little bit too lazy to implement my own complex set of error-codes, variables and functions. Is it acceptable to use the errno facility provided by the libc for custom error reporting? All my errors fit into the categories given by the E... macros.

For instance, let's say my code includes a function that reads a SHA256 hash in hexdecimal notation and converts it into some sort of internal format. I want to use errnoto report errors:

#include <errno.h>

int hash_fromstr(hash_t *out, const char *in) {
  /* ... */

  if (strlen(in) != 65) {
    errno = EINVAL;
    return -1;
  }

  /* ... */
}

Of course this example is ridiculously simplified, in reality much more errors may happen in other functions.

4

2 回答 2

8

您可以随意修改 errno 的值,只要确保您的库代码在这样做之前检查 errno 是否未设置,以确保您的库代码仍然可以正确检测导致设置 errno 的内部标准故障。您还可以查看“我应该设置 errno”以获取更多信息。

于 2012-05-14T21:24:31.107 回答
1

是的,您可以对其进行修改,并且它具有线程范围,这在这种错误处理中是非常可取的。

使用 errno 错误系列 ( E...) 并可能对其进行扩展,这可能是一种非常强大但简单的错误处理模式。它可能被其他人认为是不好的方法,但恕我直言,它产生更清晰的代码和用于错误处理的标准化模式。

于 2014-10-28T17:12:59.520 回答