0

In this following code, i want to use predefined message for my errors_manager function, with the macro CALL_MSG(). but when i use an variable, i can't get the content of the variable !

err = ILLOPS = 1;
CALL_MSG(err)
error: ‘MSG_err’ undeclared (first use in this function)

but when i use a integer that work prefectly :/

ft_putstr(CALL_MSG(err));
print: illegal option -- 

How i can made a similar system for my messages (Using defines and enums if possible)

errors.h

#ifndef ERRORS_H
# define ERRORS_H

# define CALL_MSG(var) MSG_ ## var
# define MSG_1 "illegal option -- "

enum            e_errors
{
    NOT,
    ILLOPS = 1,
    ILLOPS_QUIT = 1,
    NFOUND
};

typedef enum e_errors t_errors;

#endif

main.c

void            err_manager(int errnum, t_errors err)
{
    ft_putstr("\033[91mls: ");
    if (err != 0)
        ft_putstr(CALL_MSG(err));
    if (errno != 0)
        ft_putendl(strerror(errno));
    ft_putstr("\033[0m");
    errnum = errnum;
    return ;
}

int     main(int ac, char **av, char **env)
{
    printf("Vous avez %d arguments\n", ac - 1);
    printf("PWD: %s\n", get_pwd(env));
    printf("Valeur du masque: %08x\n", mask_creator(ac, av));
}

Thanks !

0

1 Answer 1

0

You cannot do this with macros and variables. Macros are expanded by the preprocessor before the code goes to the compiler; they don't exist at runtime, when variables get their value.

What you can do is to keep the strings in a runtime-accessible fashion, such as an array:

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];
}

main.c

ft_putstr(call_msg(err));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.