user2874945
user2874945

Reputation: 308

How to check if Environment variable is set from C in macro

I want to call a logging function if an environment variable is set, kind of like so:

if(getenv("Log")){
    //Log("blah");
} else {
    //do nothing
}

Except, if I have it as a macro defined, then it might be cleaner.

Also, what is the correct way to do so, for C coding practices.

Upvotes: 1

Views: 1955

Answers (2)

Random832
Random832

Reputation: 39000

Really it would be much better integrate this into your logging function itself. For example, this function will check for the environment variable and then log to stderr, using the same format strings as printf:

int debug_log(const char *fmt, ...) {
    char *env = getenv("DO_DEBUG_LOG");
    if(!env || !*env) return;
    // don't log if it is unset or a blank string
    else {
        va_list ap;
        va_start(ap, fmt);
        vfprintf(stderr, fmt, ap);
        va_end(ap);
    }
}

This could be extended by, for example, interpreting the environment variable as a number and having a number passed in for the priority of the log entry (so if it's only set to 1, don't print something that has 2 or more).

Generally programs that use a macro for this are making the decision based on another macro, not an environment variable. The advantage in those cases is avoiding the overhead of a function call in the non-debug version, which you aren't really doing here since you're calling getenv every time.

Upvotes: 4

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37924

You could define macro, that encapsulates if statement within it. This might be done as:

#include <stdio.h>
#include <stdlib.h>

#define LOG_ENV(s)           \
    do {                     \
        if (getenv("Log"))   \
            Log(s);          \
    } while(0)

static void Log(const char *str)
{
    puts(str);
}

int main(void)
{
    LOG_ENV("blah");

    LOG_ENV("meh");

    return 0;
}

Upvotes: 3

Related Questions