如何定义具有依赖于符号调试的参数的函数

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

本文关键字:符号 依赖于 调试 参数 函数 何定义 定义      更新时间:2023-10-16

我用 -D 编译器选项定义了符号调试:-DDEBUG_VALUE。我想要一个函数,其中参数的存在取决于符号调试标志的定义或更少。

即如果定义了DEBUG_VALUE,我有

my_function(int parameter1, int  my_parameter_dependent)

否则

my_function(int parameter1)

以这种方式

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

我得到

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

我该如何解决?

(我在Unix系统上使用C++编译器。

你可以以不同的方式声明函数...

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

创建嵌入的宏

 # 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) );

这意味着宏中的文本由预处理器咀嚼,并且是隐藏

或者,您可以声明调试数据

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

它们都有其优点,具体取决于灵活性和更改的功能数量。

不能在一行嵌入预处理器宏。他们需要自己的专用线路。因此,您必须将此声明分解为单独的行:

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

或者,如果你想变得聪明和干燥,利用C++在语句和空格方面的巨大灵活性:

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