我需要设置一种方法来从 make 文件中调试我的程序。具体来说,当我键入时,make -B FLAG=-DNDEBUG
我需要程序正常运行。但是当这个标志不存在时,我需要assert()
在整个代码中运行一些命令。
为了澄清我需要知道如何检查我的 C 代码中是否不存在这个标志,我认为它与#ifndef
,我只是不知道从那里去哪里。
原谅我的无知,任何回应将不胜感激!
我需要设置一种方法来从 make 文件中调试我的程序。具体来说,当我键入时,make -B FLAG=-DNDEBUG
我需要程序正常运行。但是当这个标志不存在时,我需要assert()
在整个代码中运行一些命令。
为了澄清我需要知道如何检查我的 C 代码中是否不存在这个标志,我认为它与#ifndef
,我只是不知道从那里去哪里。
原谅我的无知,任何回应将不胜感激!
在使用或不使用“FLAG=-DNDEBUG”调用 make 时,您的 Makefile 中将需要这样的规则:
%.o: %.c
gcc -c $(FLAG) $<
在您的 C 代码中,您将需要如下内容:
#ifndef NDEBUG
fprintf(stderr, "My trace message\n");
#endif
假设您正在谈论assert
标准库(#define
d in <assert.h>
)中的宏,那么您不必做任何事情。图书馆已经照顾好NDEBUG
标志。
如果您想让自己的代码仅在宏是 / 不是#define
d 时才执行操作,请使用#ifdef
您在问题中已经怀疑的 an 。
例如,我们可能有一个条件过于复杂而无法放入单个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;
}
请注意,这种编码风格会导致代码难以阅读,并且需要极难调试的Heisenbug 。表达这一点的更好方法是使用函数。
/* 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;
}