【问题标题】:Debugging using makefile flags in C在 C 中使用 makefile 标志进行调试
【发布时间】:2015-10-15 05:21:36
【问题描述】:

我需要设置一种方法来从 make 文件中调试我的程序。具体来说,当我输入make -B FLAG=-DNDEBUG 时,我需要程序正常运行。但是当这个标志不存在时,我需要在整个代码中运行一些assert() 命令。

为了澄清我需要知道如何检查我的 C 代码中是否不存在此标志,我假设它与 #ifndef 有关,我只是不知道从那里去哪里。

请原谅我的无知,任何回复将不胜感激!

【问题讨论】:

    标签: c debugging makefile compiler-flags ifdefine


    【解决方案1】:

    假设您正在谈论标准库中的assert 宏(#defined in <assert.h>),那么您无需执行任何操作。该库已经处理了NDEBUG 标志。

    如果您想让自己的代码仅在宏是 / 不是 #defined 时才执行操作,请使用 #ifdef,正如您在问题中已经怀疑的那样。

    例如,我们可能有一个条件过于复杂,无法放入单个 assert 表达式中,因此我们需要一个变量。但是如果assert 扩展为空,那么我们不希望计算该值。所以我们可能会使用这样的东西。

    int
    questionable(const int * numbers, size_t length)
    {
    #ifndef NDEBUG
      /* Assert that the numbers are not all the same. */
      int min = INT_MAX;
      int max = INT_MIN;
      size_t i;
      for (i = 0; i < length; ++i)
        {
          if (numbers[i] < min)
            min = numbers[i];
          if (numbers[i] > max)
            max = numbers[i];
        }
      assert(length >= 2);
      assert(max > min);
    #endif
      /* Now do what you're supposed to do with the numbers... */
      return 0;
    }
    

    请注意,这种编码风格会使代码难以阅读,并且 要求 Heisenbugs 极难调试。更好的表达方式是使用函数。

    /* 1st helper function */
    static int
    minimum(const int * numbers, size_t length)
    {
      int min = INT_MAX;
      size_t i;
      for (i = 0; i < length; ++i)
        {
          if (numbers[i] < min)
            min = numbers[i];
        }
      return min;
    }
    
    /* 2nd helper function */
    static int
    maximum(const int * numbers, size_t length)
    {
      int max = INT_MIN;
      size_t i;
      for (i = 0; i < length; ++i)
        {
          if (numbers[i] > max)
            max = numbers[i];
        }
      return max;
    }
    
    /* your actual function */
    int
    better(const int * numbers, int length)
    {
      /* no nasty `#ifdef`s */
      assert(length >= 2);
      assert(minimum(numbers, length) < maximum(numbers, length));
      /* Now do what you're supposed to do with the numbers... */
      return 0;
    }
    

    【讨论】:

      【解决方案2】:

      在使用或不使用“FLAG=-DNDEBUG”调用 make 时,您的 Makefile 中需要这样的规则:

      %.o: %.c gcc -c $(FLAG) $<

      在您的 C 代码中,您将需要这样的内容:

      #ifndef NDEBUG
        fprintf(stderr, "My trace message\n");
      #endif
      

      【讨论】:

        猜你喜欢
        • 2015-09-09
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多