I wrote a simple logging function which displays a timestamp and uses vprintf() to emulate printf(). Now, my main program is reading a configuration file into a struct configuration. I plan on making the logging function use this configuration to determine where it should log to (std{out,err}, syslog, some other file, …). So, what would be the best way to make my logging function know where it should log to? I’m thinking of making my struct configuration * config a global variable, declared just before main() and having extern struct configuration * config in log.h so that log.c can use it. But everybody keeps on saying “global variables are bad, don’t use them” so I’d like to know if there’s a better way to do it.
I wrote a simple logging function which displays a timestamp and uses vprintf() to
Share
Well, global configuration needs to be global. So, I would consider that an exception to the rule. However, you may want to expose the
structasconstin most cases. That would help narrow down what modules are changing the global state in the future.To accomplish this, use a global function that exposes a
constpointer instead of a directextern. In fact, you could declare the configurationstructasstaticas well. That would further eliminate unexpected access.