Home > Enterprise >  store or check value of getenv() only once in a shared library/DLL
store or check value of getenv() only once in a shared library/DLL

Time:09-21

I have a function to print debug logs which has to be toggled depending on the environment variable. Instead of checking the env var each time the print_trace() is called, what should be the best method to store it and reuse that value?

void print_trace(const char* msg)
{
    const char* s = getenv("DEBUG_TRACE");

    if(!strcmp(s,"ON"))
      printf(msg);
}

There is no main() as this is a shared library.

CodePudding user response:

You could save the result of the decision in a static variable.

void print_trace(const char* msg)
{
    static int debug_on = -1; // -1 == not yet set
    if (debug_on == -1) {
        const char* s = getenv("DEBUG_TRACE");
        debug_on = s && (strcmp(s, "ON") == 0);
    }

    if(debug_on)
      printf("%s", msg);
}

CodePudding user response:

You could use the thread safe call_once feature that was added in C11.

Example:

#include <threads.h>

static bool debug_mode;                   // your debug mode flag

void set_debug_mode(void) {               // this is only called once
    const char *s = getenv("DEBUG_TRACE");
    debug_mode = s && !strcmp(s, "ON");
}

void print_trace(const char* msg) {
    static once_flag flag = ONCE_FLAG_INIT;
    call_once(&flag, set_debug_mode);     // called once to set debug_mode

    if(debug_mode)
        printf(msg);
}
  • Related