【问题标题】:C++: Scoping issues when using a debug variable for a programC++:为程序使用调试变量时的范围问题
【发布时间】:2014-10-10 08:17:07
【问题描述】:

我正在编写一个程序,我想轻松地打开/关闭我的调试代码。这个程序不是生产级别的——它是用于编程比赛的。

我只有一个文件main.cpp,所以我认为调试变量可能是可以接受的。我考虑过使用全局变量,如下:

bool DEBUG = true;

int main()
{

    if (DEBUG)
    {
         // print debug statements and other debug code
    }
    // rest of program...

但是,我收到警告说我的 DEBUG 变量从未使用过,if (DEBUG) 始终评估为假。或者,我可以将我的 DEBUG 变量带入 main() 方法:

int main()
{
    bool DEBUG = true;
    if (DEBUG)
    {
         // print debug statements and other debug code
    }
    // rest of program...

然后我收到编译器警告“条件始终为真. Any suggestions on how to easily switch on/off myDEBUG”代码?对编译器问题的解释会很好。

【问题讨论】:

  • 通常这些标志是使用一些外部刺激设置的。例如reg 键设置。您应该对此进行探索。

标签: c++ debugging scope global-variables


【解决方案1】:

常用的方法是使用预处理器

#ifndef NDEBUG
// debug code
#endif

// or

#ifdef DEBUG
// debug code
#endif

虽然我在 NDEBUG 上工作的一个项目未定义并被另一个项目替换,因此请检查它是否存在。

您的警告是因为还有一个#define DEBUG 已经存在,我也不会感到惊讶。所以你的变量 DEBUG 永远不会被使用。

通常 DEBUG 和 NDEBUG 由编译器定义。

【讨论】:

    【解决方案2】:

    [...] 我想轻松打开/关闭我的调试代码 [...] 有关如何轻松打开/关闭 myDEBUG` 代码的任何建议?

    考虑一下:

    bool debug = false; // set default value on compilation
    int main(int argc, char **argv)
    {
        using std::literals::string_literals;
    
        std::vector<std::string> args{ argv, argv + argc };
        if(std::end(args) != std::find(std::begin(args), std::end(args), "-d"s))
            debug = true; // reset debug flag based on runtime parameter
        // use debug from this point onwards
    }
    

    用法:

    $ ./your-app # run with compiled flag
    $ ./your-app -d # run with debug information
    

    注意事项:

    • "-d"s 构造需要using std::literals::string_literals;
    • 您可以根据编译宏设置默认调试标志(DEBUG、_DEBUG 和 NDEBUG 在 Windows 上最常见)
    • 如果您需要更复杂的参数处理,请考虑使用boost::program-options

    【讨论】:

      猜你喜欢
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      相关资源
      最近更新 更多