Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a function with a parameter dependent on a symbol debug?

I defined with -D compiler option a symbol debug: -DDEBUG_VALUE. I would like a function in which the presence of a parameter depends on the definition or less of the symbol debug flag.

Namely if DEBUG_VALUE is defined, I have

my_function(int parameter1, int  my_parameter_dependent)

Otherwise

my_function(int parameter1)

In this way

my_function(int parameter1  #ifdef DEBUG_VALUE , int my_parameter_dependent #endif)

I get

error: stray ‘#’ in program
error: expected ‘,’ or ‘...’ before ‘ifdef’

How can I solve it?

(I'm on a C++ compiler on a Unix system.)

like image 489
Nick Avatar asked May 29 '26 16:05

Nick


2 Answers

You can declare the function differently...

 #if defined( DEBUG_VALUE )
     void my_function( int parameter1, int my_parameter_dependent );
 #else
     void my_function( int parameter1 );
 #endif

Create an embedded macro

 # if defined( DEBUG_VALUE )
         #define DEPENDENT_PARAM( x )   x
 # else
         #define DEPENDENT_PARAM( x )
 #endif
 void my_function( int parameter1  DEPENDENT_PARAM(, int my_parameter_dependent) );

This means that the text within the macro is munched by the preprocessor, and is hidden

Or you can declare debug data

  #if defined( DEBUG_VALUE )
      #define EXTRA_DEBUG  , int my_parameter_dependent
  #else
      #define EXTRA_DEBUG
  #endif
  void my_function( int parameter1 EXTRA_DEBUG );

They all have their merits, depending on flexibility and how many functions are changed.

like image 133
mksteve Avatar answered May 31 '26 05:05

mksteve


You can't embed a preprocessor macro within a line. They require a dedicated line of their own. So you have to break this declaration up onto separate lines:

#ifdef DEBUG_VALUE
    void my_function(int parameter1, int my_parameter_dependant);
#else
    void my_function(int parameter1);
#endif

Or, if you want to get clever and DRY, take advantage of C++'s great flexibility with regard to statements and whitespace:

void my_function(int parameter1
#ifdef DEBUG_VALUE
                , int my_parameter_dependant
#endif
                );
like image 43
Cody Gray Avatar answered May 31 '26 05:05

Cody Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!