c - 在 C 中实现详细

标签 c verbose

我正在实现详细模式。这是我尝试做的事情:定义一个全局变量 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;
}

ma​​in.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/

相关文章:

c - 如何将二维数组的每个元素递增 2

C:将 4 个字节写入大小为 3 的区域会溢出目标吗?

php cURL CURLOPT_VERBOSE 不显示负载

java - 调试 Java 8 过滤器

java - 我们可以在 java 中实现的性能改进功能列表

c - 备注: unrecognized token warning for the macro concatenation

c - 文件记录排序的高效算法

c - CHS 磁盘几何的可能来源

php - MySQL任务的即时可视化

java - 在java中打开/关闭println的任何方法(详细模式)