c - 选择合适的错误报告机制 : How can I change a macro at compile time?

标签 c macros exit

我希望我的程序从每个不正确的退出中报告不同的退出代码,比如

fprintf(stderr, "bad foo in bar (%d)", -1);
exit(-1);
...
fprintf(stderr, "bad baz in qux (%d)", -2);
exit(-2);
...
fprintf(stderr, "bad boop in bing (%d)", -3);
exit(-3);

可以调用每个地方的导出等等。由于维护位置数可能会很痛苦,所以我想使用宏:

MY_ERR("...")

扩展为

do{ fprintf("...""(%d)", --EXITCODE);
    exit(EXITCODE); } while(0);

那么问题就变成了,EXITCODE 是什么?如果它是一个普通的 C 变量,那么它只会在运行时递减,并且会立即退出,所以每个错误都不会有唯一的编号,并且该编号将始终为 -1(如果 EXITCODE 从 0 开始)。但如果它是一个 #defined 宏,那么我们就不能递减它。

有没有办法做我想做的事?我想我可以使用 __LINE__,但这不适用于多个文件。我可以结合使用 __FILE____LINE__,但这不能是退出的代码。

最佳答案

显而易见的解决方案是创建一个包含所有错误代码的表格。枚举或常量数组。无论如何,您需要某种关于这些魔数(Magic Number)含义的文档。

例如:

错误.h

typedef enum
{
  ERR_BAD_FOO,
  ERR_BAD_BAZ,
  ERR_BAD_BOOP,
  ERRORS_N
} err_t;

void error_then_exit (err_t error);

错误.c

#include "errors.h"

void error_then_exit (err_t error)
{
  const char* ERR_STR [] =
  {
    "bad foo in bar",
    "bad baz in qux",
    "bad boop in bing"
  };

  _Static_assert(ERRORS_N == sizeof(ERR_STR)/sizeof(*ERR_STR), 
                 "Errors in the error handler!");

  int code = -(int)error;

  fprintf(stderr, "%s (%d)\n", ERR_STR[error], code);
  exit(code);
}

用法:

#include "errors.h"

error_then_exit (ERR_BAD_FOO);

关于c - 选择合适的错误报告机制 : How can I change a macro at compile time?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36065552/

相关文章:

c - 从函数加载运行器返回值

c++ - 为项目文本文件定义宏

c++ - 拦截 WM_CLOSE 进行清理操作

c - C 中的 Malloc 断言失败

c - 为什么我们在 getopt() 函数中使用 argc 作为参数?

c - 执行 While 循环。这不起作用

java - JFrame 在关闭时拦截退出以保存数据

c++ - 带宏的模板函数 - 在 vector 上累积

c - 如何将可变参数函数调用作为宏定义?

python - 从 Python 执行 C 函数时防止 exit(1) 退出 Python