【发布时间】:2016-07-05 21:19:34
【问题描述】:
我正在实现详细模式。这是我尝试做的事情:以需要详细的文件只需要包含该文件的方式定义全局变量 VERBOSE(在 verbose.h 中)。例如:
verbose.h:
void setVerbose(int test);
verbose.c:
#include "verbose.h"
// define VERBOSE if called
void setVerbose(int test) {
if (test) {
#ifndef VERBOSE
#define VERBOSE
#endif
}
}
point.h:
typedef struct Point Point;
struct Point {
int x, y;
};
void printPoint(Point *point);
point.c:
#include "point.h"
#include "verbose.h"
void printPoint(Point *point) {
#ifdef VERBOSE
printf("My abscissa is %d\n", point->x);
printf("My ordinate is %d\n", point->y);
#endif
printf("[x,y] = [%d, %d]\n", point->x, point->y);
}
还有主要的:
main.c:
#include "verbose.h"
#include "point.h"
int main(int argc, char *argv[]) {
if (argc >= 2 && !strcmp(argv[1], "-v"))
setVerbose(1);
Point *p = init_point(5,7);
printPoint(p);
return 0;
}
可执行文件已生成:
$ gcc -o test main.c point.c verbose.c
想要的输出是:
$ ./test
[x,y] = [5, 7]
$ ./test -v
My abscissa is 5
My ordinate is 7
[x,y] = [5, 7]
问题是,调用 printPoint() 时似乎没有在 point.c 中定义 VERBOSE。
【问题讨论】:
-
请重新阅读预处理器的概念。
-
#define是一个 预处理器 指令。在 if 语句中放置 #define 是没有意义的。#define在程序编译之前被翻译。 -
其他人已经提到了这个问题,因此我只建议您使用 logging class 而不是您当前的方法。它更加灵活。比如我前段时间给Arduino写了一篇abrushforeachkeyboard.wordpress.com/2014/06/17/…
-
@PatrickTrentin 那是 C++,所以在这种情况下可能不适用。对于作者来说,如果你想看到一个最低限度的日志记录解决方案,你可以看看我写的 C 记录器。我很确定它可以工作,:-) 并且有一个你正在尝试做的例子github.com/ccs19/CCS_CLogger
-
@ChristopherSchneider 当然,它还包含对他根本无法运行的库的引用。这只是为了暗示一个更好的想法来处理多功能日志记录。您的解决方案也很震撼。 :)