我正在实现详细模式。这是我尝试做的事情:定义一个全局变量 VERBOSE(在 verbose.h 中),这样需要详细的文件只需要包含该文件。例如:
详细.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
}
}
点.h:
typedef struct Point Point;
struct Point {
int x, y;
};
void printPoint(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);
}
主要是:
主.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。
最佳答案
预处理器命令是在编译时决定的,而不是运行时,所以你的系统不会工作。我建议改为使用全局 bool Verbose
并提供 verbose()
函数来执行(或不执行)打印。
verbose.h
#include <stdbool.h>
int verbose(const char * restrict, ...);
void setVerbose(bool);
verbose.c
#include "verbose.h"
#include <stdbool.h>
#include <stdarg.h>
#include <stdio.h>
bool Verbose = false;
void setVerbose(bool setting) {
Verbose = setting;
}
int verbose(const char * restrict format, ...) {
if( !Verbose )
return 0;
va_list args;
va_start(args, format);
int ret = vprintf(format, args);
va_end(args);
return ret;
}
main.c
#include "verbose.h"
#include <stdbool.h>
int main() {
verbose("Verbose is off\n");
setVerbose(true);
verbose("Verbose is on\n");
int foo = 42;
verbose("Number: %d\n", foo);
return 0;
}
关于c - 在 C 中实现详细,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36095915/