在 C 语言中为库设计 public 个错误代码

Designing public error codes in C for a library

我试图解决的一个设计问题是什么是使客户端能够处理调用库函数时可能发生的错误的灵活方法。我看到 2 种方法:

I. 将任何库函数引发的所有错误放在 public 单独的头文件中,例如 lib_errors.h:

#define APP_ERR_OBJECT_TOO_SMALL 1 /* The object is too small */

#define APP_ERR_HOST_UNREACHABLE 2 /* Host is not reachable */

#define APP_ERR_UNKNOWN          3 /* Unknown error */

并将其包含在库的所有 public 头文件中。

header1.h:

#include "lib_errors.h"

/**
 * -1 - on error 
 *      error_code is set to APP_ERR_OBJECT_TOO_SMALL the buf is too small
 *      error_code is set to APP_ERR_UNKNOWN in case of unknown error
 */ 
int hdr1_drain(void *buf, size_t sz, int *error_code);

header2.h:

#include "lib_errors.h"

/**
 * -1 - on error 
 *      error_code is set to APP_ERR_HOST_UNREACHABLE if the host is unreachable
 *      error_code is set to APP_ERR_UNKNOWN in case of unknown error
 */ 
int hdr2_connect(char *add, int *error_code);

我看到的问题:库可以引发的所有错误都将包含在每个头文件中,即使是头文件本身不会引发的错误。

II. 在每个头文件中定义一个特定于头的错误:

header1.h:

#define HDR1_OBJECT_TOO_SMALL 1
#define HDR1_UNKNOWN          2

header2.h

#define HDR2_HOST_UNREACHABLE 1
#define HDR2_UNKNOWN          2

我看到的问题:代码重复的数量随着常见错误的增加而增加。所有常见错误都必须在每个 public 头文件中重复。

所以我目前很困惑该选择哪一个。可能还有另一种方法来解决设计问题。第一种方法似乎更接近 POSIX errno.

您可以结合使用这两种方法。将所有常见错误放在一个 header 中,然后将 application-specific 错误放在应用 header.

lib_errors.h:

#define ERR_UNKNOWN 1
...
#define LIBERR_LAST 100

header1.h:

#include "lib_errors.h"

#define HDR1_OBJECT_TOO_SMALL (LIBERR_LAST + 1)
...

header2.h:

#include "lib_errors.h"

#define HDR2_HOST_UNREACHABLE (LIBERR_LAST + 1)
...