tags:

views:

46

answers:

2

Hello,

gcc 4.4.2 c89

I have the following code.

#if defined ( __linux__ )
    log_msg(stderr, "Socket failed [ %s ] [ %s ] [ %d ]\n",
        strerror(errno), __func__, __LINE__);

#elif ( WIN32 )
    log_msg(stderr, "Socket failed [ %s ] [ %s ] [ %d ]\n",
        strerror(errno), __FUNCTION__, __LINE__);
#endif

Because I am compiling on both windows and linux I have to separate is log_msg as above as they use different macros for getting the function name FUNCTION AND func.

However, I have many of these log_msg to write and just wondering is there anyway I can avoid having to write this twice for the sake of one macro being different?

many thanks for any advice,

+5  A: 

Why not do something like this?

#if defined ( __linux__ )
    #define FUNC_REF __func__
#elif ( WIN32 )
    #define FUNC_REF __FUNCTION__
#endif

log_msg(stderr, "Socket failed [ %s ] [ %s ] [ %d ]\n",
    strerror(errno), FUNC_REF, __LINE__);

edit: you could of course avoid using a new constant by defining one to be the other (ie #define __func__ __FUNCTION__ for the WIN32 condition.)

Mark E
25 lousy seconds for the exact same answer.
Chris Doggett
@Chris, good race.
Mark E
Thanks, I probably could've won if I'd written any C in the past 8 years and hadn't had to look up the proper way to #define something.
Chris Doggett
+5  A: 

Instead of doing this solution, I would use the recomended work around suggested by the GCC compiler. Essentially define the following macro and use __func__ everywhere

 #if __STDC_VERSION__ < 199901L
 # if __GNUC__ >= 2
 #  define __func__ __FUNCTION__
 # else
 #  define __func__ "<unknown>"
 # endif
 #endif

Reference: http://gcc.gnu.org/onlinedocs/gcc-3.4.0/gcc/Function-Names.html

JaredPar