我想添加一些C

void foo()
{   
  // ...
  #ifdef DEBUG
  static bool s_bDoDebugOnlyCode = false;
  if (s_bDoDebugOnlyCode)
  {
      // Debug only code here gets executed when the person debugging 
      // manually sets the bool above to true.  It then stays for the rest
      // of the session until they set it to false.
  }
  #endif
 // ...
}

我不能做同样的在C

Question: 在 C 中实现此目的的最佳方法是什么

  1. 我应该使用一个私人和C类静态字段吗#if/#endif DEBUG)?
  2. 我应该使用条件属性(保存代码),然后使用私有类静态字段(not C包围#if/#endif DEBUG?)。
  3. 还有别的事吗?

答案

实例变量可能是执行您想要的操作的方法。

#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif

void foo()
{   
  // ...
#if DEBUG
  if (s_bDoDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }
#endif
 // ...
}

为了完整起见,编译指示(预处理器指令)被认为是用来控制程序流程的有点混乱。

private /*static*/ bool doDebugOnlyCode = false; 
[Conditional("DEBUG")]
void foo()
{   
  // ...    
  if (doDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }    
  // ...
}

没有编译指示,更干净。

来自: stackoverflow.com