[C/C++][Tip] Macro...

Language/C&C++ 2006.11.17 23:45
[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

====================================================

// 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 :
#ifdef CODE_DEBUG
#   define REAL_fnc(a, b) real_fnc(a, b, __FILE__, __LINE__)
#else
#   define REAL_fnc(a,b) real_fnc(a,b)
#endif

But, In following cases, some compiler raises error.

#ifdef 1
REAL_fnc(a,
#else
NEW_REAL_fnc(a,
#endif
    b);

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

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

---------

// foo_fnc.c
...(omitted)
RealType_Fnc real_fnc_wrap(char* fileName, int line)
{
    printf(“%s : %d”, fileName, line);
    return real_fnc;
}
신고
tags : ,
Trackback 0 : Comment 0