3

我正在实施详细模式。这是我尝试做的事情:以需要详细的文件只需要包含该文件的方式定义全局变量 VERBOSE(在 verbose.h 中)。例如 :

详细的.h:

void setVerbose(int test);

详细的.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。

4

1 回答 1

6

预处理器命令是在编译时决定的,而不是在运行时决定的,因此您的系统将无法工作。相反,我建议使用全局bool Verbose并提供verbose()打印(或不打印)的功能。

详细的.h

#include <stdbool.h>

int verbose(const char * restrict, ...);
void setVerbose(bool);

详细的.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;
}

主程序

#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;
}
于 2016-03-18T23:40:45.013 回答