C ++ Replacing functions with macros

We have an existing implementation of the function in our C ++ code:

void Function(int param)
{
    printf("In Function\n");
}

int main()
{
    Function(10);
    return 0;
}

      

I want to change it to call another function (using a macro declaration) that will take additional parameters like FILE and LINE (for debugging purpose) and then call the actual function:

#define Function(param) Function_debug(param, __FILE__,  __FUNCTION__,  __LINE__) \
{\
    printf("In Function_debug [%s] [%s] [%d]\n", file, func, line); \
    Function(param);\
}

      

But the below code:

#include <stdio.h>

#define Function(param) Function_debug(param, __FILE__,  __FUNCTION__,  __LINE__) \
{\
    printf("In Function_debug [%s] [%s] [%d]\n", file, func, line); \
    Function(param);\
}

void Function(int param)
{
    printf("In Function\n");
}

int main()
{
    Function(10);
    return 0;
}

      

Translates TO:

void Function_debug(int param, "temp.cpp", __FUNCTION__, 9) { printf("In Function_debug [%s] [%s] [%d]\n", file, func, line); Function(int param);}
{
    printf("In Function\n");
}

int main()
{
    Function_debug(10, "temp.cpp", __FUNCTION__, 16) { printf("In Function_debug [%s] [%s] [%d]\n", file, func, line); Function(10);};
    return 0;
}

      

which gives compilation errors.

Please guide me how to achieve the goal?

+2


source to share


4 answers


You usually do something like this:



#if DEBUG
#define FUNCTION(param) Function_debug(param, __FILE__,  __FUNCTION__,  __LINE__)
#else
#define FUNCTION(param) Function(param)
#endif

void Function(int param)
{
    printf("In Function\n");
}

void Function_debug(int param, const char * file,  const char * func,  int line)
{
    printf("In Function_debug [%s] [%s] [%d]\n", file, func, line); \
    Function(param);
}

int main()
{
    FUNCTION(10);
    return 0;
}

      

+6


source


1st rule: use a different name for your macro and the function it replaces.
2nd rule: if you are using gcc, wrap the code block in parentheses ({}) so that your functions are called as ifprintf("%f\n",sqrt(2.0));



#define Function(a) ({ printf("Debug stuff\n"); orig_function(a);})

0


source


You must first implement the second function, and then in your macro just redirect your code to it, in your version you implement the whole function that uses the macro:

void function( int param )
{
    // do something interesting here
}
void function_debug( int param, char const* fileName, unsigned line, char const* fn)
{
    // debug position here
    function( param );
}

#ifndef NDEBUG
#    define Function( param )    function_debug( param, __FILE__, __LINE__, __FUNCION__ )
#else
#    define Function( param )    function( param )
#endif

      

0


source


Can't you add debug printing to Function

?

void Function(int param)
{
    #ifdef DEBUG
    //debug stuff
    #endif
    printf("In Function\n");
}

      

0


source







All Articles