Implementing verbose in C

Eamnea picture Eamnea · Mar 19, 2016 · Viewed 7k times · Source

I'm implementing a verbose mode. Here's what I attempt to do : defining a global variable VERBOSE (in verbose.h) in such way that files requiring verbose only need to include that file. For example :

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);
}

And the main :

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;
}

The executable has been produced with :

$ gcc -o test main.c point.c verbose.c

The outputs wanted are :

$ ./test
    [x,y] = [5, 7]

$ ./test -v
    My abscissa is 5
    My ordinate is 7
    [x,y] = [5, 7]

Problem is, it seems that VERBOSE is not defined in point.c when calling printPoint().

Answer

Schwern picture Schwern · Mar 19, 2016

Preprocessor commands are decided at compile time, not run time, so your system won't work. What I would recommend instead is using a global bool Verbose and providing a verbose() function to do the printing (or not).

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;
}