Use typedef within struct for naming and indexing text commands

前端 未结 2 488
甜味超标
甜味超标 2021-01-15 02:34

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

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-15 03:13

    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).

提交回复
热议问题