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 to share
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 to share