Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cross-compiling macro names

Tags:

c

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,

like image 394
ant2009 Avatar asked Dec 29 '22 04:12

ant2009


2 Answers

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.)

like image 170
Mark Elliot Avatar answered Dec 31 '22 19:12

Mark Elliot


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

like image 38
JaredPar Avatar answered Dec 31 '22 17:12

JaredPar