[C/C++][Tip] Macro…


// From MSDN

#define paster( n ) printf( "token" #n " = %d", token##n )
int token9 = 9;

If a macro is called with a numeric argument like

paster( 9 );

the macro yields

printf( "token" "9" " = %d", token9 );

which becomes

printf( "token9 = %d", token9 );


‘,’ is used as parameter separator in C/C++. So, function which uses variable number of parameter – like “logger(const char* format, …)” – is difficult to present by using macro. (Some compilers support variable number of parameter in macro too. But, most are not.)
In this case, we can make those be on parameter by groupping all parameters with “()”.
For example,

#ifdef _DEBUG_
#   define LOGGER(X) logger X
#else // _DEBUG_
// we don't need to run log function in release build!
#   define LOGGER(X)
#endif // _DEBUG_
LOGGER((”print :%d, %d”, a, b)); // == logger(“print:%d, %d”, a, b);


To track a function, following way is very common.

// foo_fnc. h :
#   define REAL_fnc(a, b) real_fnc(a, b, __FILE__, __LINE__)
#   define REAL_fnc(a,b) real_fnc(a,b)

But, In following cases, some compiler raises error.

#ifdef 1

Yes. It’s a kind of porting issue.
In this case, we can use following walk-around.

// foo_fnc. h :
    typedef int (* RealType_Fnc)(int, int)
#   define REAL_fnc real_fnc_wrap(__FILE__, __LINE__)
    extern RealType_Fnc real_fnc_wrap(char*, int);
#   define REAL_fnc(a,b) real_fnc(a,b)


// foo_fnc.c
RealType_Fnc real_fnc_wrap(char* fileName, int line)
    printf(“%s : %d”, fileName, line);
    return real_fnc;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s