Macro and function with same name

前端 未结 5 869
我在风中等你
我在风中等你 2020-12-01 15:00

I have the following code

#define myfunc(a,b) myfunc(do_a(a), do_b(b))

void myfunc(int a, int b)
{
  do_blah(a,b);
}
int main()
{
    int x = 6, y = 7;
             


        
相关标签:
5条回答
  • 2020-12-01 15:37

    Use () to stop the preprocessor from expanding the function definition:

    #include <stdio.h>
    
    #define myfunc(a, b) myfunc(do_a(a), do_b(b))
    /* if you have a preprocessor that may be non-standard
     * and enter a loop for the previous definition, define
     * myfunc with an extra set of parenthesis:
    #define myfunc(a, b) (myfunc)(do_a(a), do_b(b))
     ******** */
    
    int (myfunc)(int a, int b) /* myfunc does not get expanded here */
    {
        printf("a=%d; b=%d\n", a, b);
        return 0;
    }
    
    int do_a(int a)
    {
        return a * 2;
    }
    
    int do_b(int b)
    {
        return b - 5;
    }
    
    int main(void)
    {
        myfunc(4, 0);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 15:45

    I see three possible solutions:

    • define your macro after function definition.

    • define, before the function definition, do_a() and do_b() such that they return their argument, and redefine them at your will after function definition

    • perform do_a() and do_b() inside the function:

      void myfunc(int a, int b)
      {
          do_blah(do_a(a),do_b(b));
      }
      

    I have a strong preference for the latter.

    0 讨论(0)
  • 2020-12-01 15:54

    Define the macro after the defintion of the function.

    void myfunc(int a, int b)
    {
      do_blah(a,b);
    }
    
    #define myfunc(a,b) myfunc(do_a(a), do_b(b))
    
    int main()
    {
        int x = 6, y = 7;
        myfunc(x,y);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 15:59

    Why can you not change the source code? At worst, if you need to maintain the original version, run a patch on it to create a temporary file in which the function is renamed and build it from there.

    0 讨论(0)
  • 2020-12-01 16:02

    Define the macro after you define the function.

    Alternatively, use a pattern like this:

    #define myfunc_macro(a,b) myfunc(do_a(a), do_b(b))
    #define myfunc(a,b) myfunc_macro(a,b)
    
    .
    .
    
    #undef myfunc
    void myfunc(int a, int b)
    {
      do_blah(a,b);
    }
    #define myfunc(a,b) myfunc_macro(a,b)
    
    .
    .
    
    int main()
    {
        int x = 6, y = 7;
        myfunc(x,y);
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题