I am working with a simple command line application that takes in ASCI text and interprets it as a command.
I have attempted to minimize the redundancy in this appli
You can use macro redefinition to achieve this. First, you create a file that simply lists your commands called commands.inc
:
COMMAND(quit)
COMMAND(help)
...
Then, in your C source you can #include "commands.inc"
multiple times, with different definitions of COMMAND()
in effect to control how it works. For example:
struct command
{
char *name;
int command_idx;
};
#define COMMAND(NAME) CMD_ ## NAME,
enum command_enum {
#include "commands.inc"
};
#undef COMMAND
#define COMMAND(NAME) { #NAME, CMD_ ## NAME },
struct command commands[] =
{
#include "commands.inc"
};
#undef COMMAND
(Note that this particular example relies on a C99 improvement that allows a trailing ,
at the end of the lists in the enum
declaration and compound initialiser - you can easily work around that in C89 by adding a dummy entry at the end).