Making something both a C identifier and a string?

前端 未结 2 1570
攒了一身酷
攒了一身酷 2020-12-13 10:49

Say you want to generate a matched list of identifiers and strings

enum
{
NAME_ONE,
NAME_TWO,
NAME_THREE
};

myFunction(NAME_ONE, \"NAME_ONE\");
myFunction(N         


        
相关标签:
2条回答
  • 2020-12-13 11:37

    For your second #define, you need to use the # preprocessor operator, like this:

    #define myDefine(a) myFunc(a, #a);
    

    That converts the argument to a string.

    0 讨论(0)
  • 2020-12-13 11:45

    Here's a good way to declare name-list:

    #define FOR_ALL_FUNCTIONS(F)\
      F(NameOne)\
      F(NameTwo)\
      F(NameThree)\
    
    #define DECLARE_FUNCTION(N)\
        void N();
    
    #define IMPLEMENT_FUNCTION(N)\
        void N(){}
    
    FOR_ALL_FUNCTIONS(DECLARE_FUNCTION);
    FOR_ALL_FUNCTIONS(IMPLEMENT_FUNCTION);
    

    This way this name-list can be re-used multiple times. I have used it for prototyping new language features, although never ended up using them. So, if nothing else, they were a great way to find dead-ends in own inventions. I wonder if it's because what they say: "macros are bad"... :)

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