Counting preprocessor macros

后端 未结 5 1985
离开以前
离开以前 2021-01-02 03:46

I have this macro code, which allows me to define both a C enum and a list of the enumerated names as strings using one construct. It prevents me from havi

相关标签:
5条回答
  • 2021-01-02 04:08

    See the suggestions Mu Dynamics 'Enums, Strings and Laziness'; these are at least related to what you're after.

    Otherwise, look at the Boost Preprocessor collection (which is usable with the C preprocessor as well as the C++ preprocessor).

    0 讨论(0)
  • 2021-01-02 04:16

    The following should work:

    #define ITEM_STRING_DEFINE(id, name) #name, // note trailing comma
    const char *itemNames[] = {
      ENUM_DEFINITIONS(ITEM_STRING_DEFINE)
    };
    
    #define TOTAL_ITEMS (sizeof itemNames / sizeof itemNames[0])
    

    Edit: Thank you to Raymond Chen for noting we don't have to worry about the unnecessary final comma in the list. (I had been misremenbering the problem for enums with strict C89 compilers, as in Is the last comma in C enum required?.)

    0 讨论(0)
  • 2021-01-02 04:16

    You can use the same technique to count the invocations.

    enum itemscounter  { 
      #define ITEM_ENUM_DEFINE(id, name) name##counter,
        ENUM_DEFINITIONS(ITEM_ENUM_DEFINE) 
      #undef ITEM_ENUM_DEFINE 
     TOTAL_ITEMS
    };
    
    0 讨论(0)
  • 2021-01-02 04:18

    I know this isn't a complete answer. You can create a macro around something like this.

    #include <stdio.h>
    
    const char * array[] = {
      "arr1", "arr2", "arr3", "arr4"
    };
    
    int main (int argc, char **argv)$
    {
      printf("%d\n", sizeof(array)/sizeof(const char *));
    }
    

    If you can modify your enum so it has continous elements you can do sth like this (from Boost)

    enum { A=0,B,C,D,E,F,N };
    const char arr[N]; // can contain a character for each enum value
    
    0 讨论(0)
  • 2021-01-02 04:19

    Would also be interested in hearing if there is a better way to achieve this without having to use macros.

    You could always use a scripting language such as ruby or python to generate .c and .h files for you. If you do it well, you can integrate your script into your Makefile.

    0 讨论(0)
提交回复
热议问题