【问题标题】:Get defines dynamically for messages获取消息的动态定义
【发布时间】:2015-01-27 16:31:49
【问题描述】:

在下面的代码中,我想为我的 errors_manager 函数使用预定义的消息,以及宏 CALL_MSG()。 但是当我使用变量时,我无法获取变量的内容!

错误 = ILLOPS = 1;
CALL_MSG(错误)
错误:“MSG_err”未声明(在此函数中首次使用)

但是当我使用一个可以完美工作的整数时:/

ft_putstr(CALL_MSG(err));
print: 非法选项 -- 

如何为我的消息创建一个类似的系统(如果可能,使用定义和枚举)

错误.h

#ifndef 错误_H # 定义 ERRORS_H # 定义 CALL_MSG(var) MSG_ ## var # 定义 MSG_1 "非法选项 --" 枚举 e_errors { 不是, ILLOPS = 1, ILLOPS_QUIT = 1, 发现 }; typedef 枚举 e_errors t_errors; #endif

main.c

void err_manager(int errnum, t_errors err) { ft_putstr("\033[91mls:"); 如果(错误!= 0) ft_putstr(CALL_MSG(err)); 如果(错误号!= 0) ft_putendl(strerror(errno)); ft_putstr("\033[0m"); 错误数字 = 错误数字; 返回 ; } int main(int ac, char **av, char **env) { printf("Vous avez %d 个参数\n", ac - 1); printf("密码: %s\n", get_pwd(env)); printf("面具价值:%08x\n", mask_creator(ac, av)); }

谢谢!

【问题讨论】:

    标签: c error-handling macros


    【解决方案1】:

    您不能对宏和变量执行此操作。宏在代码进入编译器之前由预处理器扩展;当变量获得它们的值时,它们在运行时不存在。

    您可以做的是将字符串保持为运行时可访问的方式,例如数组:

    errors.h

    char const *call_msg(t_errors err);
    

    errors.c

    char const *call_msg(t_errors err) {
      static char const *const messages[] = {
        "success -- ", // or whatever NOT is supposed to mean
        "illegal option -- ",
        "not found -- ",
        ...
      };
    
      check_if_err_is_within_array_bounds(err); // exercise for the reader
    
      return messages[err];
    }
    

    ma​​in.c

    ft_putstr(call_msg(err));
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2021-07-31
      • 2022-12-04
      • 2015-10-28
      • 2014-10-28
      相关资源
      最近更新 更多