Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/Disable LOG levels using C Macro

Tags:

c

macros

#include <stdio.h>

#define LOG_D(x)  {  printf("D:");  printf(x);}
#define LOG_E(x)  {  printf("E:");  printf(x);}

void test(void)
 {

   LOG_D("ALL is well " );
 }

I have a very huge code it has different levels of log, like above code. In the final tested library I just need only one error logs in order to reduce the code size .

so I want something like this

#define ENABLE_DEBUG_LOG 0
#define ENABLE_ERROR_LOG 1

#define LOG_D(x)  {#if(ENABLE_DEBUG_LOG==1) printf("D:");  printf(x); #endif}
#define LOG_E(x)  {#if(ENABLE_ERROR_LOG==1)  printf("E:");  printf(x);#endif}

I added this #if(ENABLE_DEBUG_LOG==1) just for explaining, I need some solution which can compile.

like image 643
putta ks Avatar asked Dec 02 '22 13:12

putta ks


2 Answers

Another option - you can just comment / uncomment ENABLE_DEBUG_LOG and ENABLE_ERROR_LOG to disable / enable corresponding log level.

// #define ENABLE_DEBUG_LOG    // disable DEBUG_LOG
#define ENABLE_ERROR_LOG       // enable ERROR_LOG

#ifdef ENABLE_DEBUG_LOG
#define LOG_D(x)  {  printf("D:");  printf(x);}
#else
#define LOG_D(x) // nothing
#endif

#ifdef ENABLE_ERROR_LOG
#define LOG_E(x)  {  printf("E:");  printf(x);}
#else
#define LOG_E(x)  // nothing
#endif
like image 65
artm Avatar answered Dec 09 '22 23:12

artm


You cannot nest preprocessor directives. But you can make two versions of your macro and define them in exclusive parts of an #if or #ifdef:

#define ENABLE_DEBUG_LOG 0

#if ENABLE_DEBUG_LOG != 0
#define LOG_D(...)  printf("D: " __VA_ARGS__)
#else
#define LOG_D(...)  // Do nothing
#endif

Here, the disabled version just "eats" the LOG_D macro and doesn't do anything. (Note that undefined macros are treated as the value 0 in #if conditionals.)

like image 26
M Oehm Avatar answered Dec 09 '22 22:12

M Oehm