Is there a way of passing macro names as arguments to nested macros without them being expanded when the outermost macro is expanded?

后端 未结 1 2088
情书的邮戳
情书的邮戳 2021-02-20 16:27

(Apologies for the long title, but I couldn\'t think of a less specific one which would be clear enough)

I need to pass the name of an (object-like) macro to a nested (f

相关标签:
1条回答
  • 2021-02-20 17:06

    If you can expand the first macro to take two arguments, you could get it to work like this:

    #define FUNC(intname, intv) int v##intname = intv
    #define CALL_FUNC(intv) FUNC(_##intv, intv)
    
    #define INT1 1
    #define INT2 2
    
    int main(void)
    {
      int INTD = 4;
    
      CALL_FUNC(INT1);
      CALL_FUNC(INT2);
      CALL_FUNC(INTD);
    }
    

    The output (from GCC), looks something like this:

    int main(void)
    {
      int INTD = 4;
    
      int v_INT1 = 1;
      int v_INT2 = 2;
      int v_INTD = INTD; // not sure if you want the value of INTD here - I guess it doesn't matter?
    }
    

    Which I guess is what you are after - if I read your question right?

    The token pasting prevents the preprocessor from expanding it out and simply generates a new token which is passed to the second macro (which then simply pastes that together to form the variable), the value (which is expanded) is passed down as the second argument..


    EDIT1: Reading more through what you are after, I'm guessing the above trick is not what you reall want...ah well..

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