I have logger.h file and defining a macro function for logging:
//logger.h:
#ifndef _LOGGER_H_
#define _LOGGER_H_
#ifdef LOG_DEBUG
ofstream debug_log("debug.log");
#define log(...) debug_log << __FILE__ << ":" << __PRETTY_FUNCTION__ << ":" << __LINE__ << "| " << __VA_ARGS__ << std::endl
#else
#define log(...)
#endif
#endif
This header file is included in multiple c files. and using log() function. g++ is giving:
/tmp/ccMAjYSm.o:(.bss+0x0): multiple definition of `debug_log'
/tmp/ccHj3w7u.o:(.bss+0x0): first defined here
/tmp/cc3LQ9GQ.o:(.bss+0x0): multiple definition of `debug_log'
/tmp/ccHj3w7u.o:(.bss+0x0): first defined here
Any clue?
If you declared LOG_DEBUG
at project-level (or in multiple translation units), they will all see the
ofstream debug_log("debug.log");
line and you'll have multiple definitions.
A possible solution: put it into a single translation unit while rendering all the others aware of its existence
Header
#ifndef _LOGGER_H_
#define _LOGGER_H_
#ifdef LOG_DEBUG
extern ofstream debug_log;
#define log(...) debug_log << __FILE__ << ":" << __PRETTY_FUNCTION__ << ":" << __LINE__ << "| " << __VA_ARGS__ << std::endl
#else
#define log(...)
#endif
#endif
A cpp file
ofstream debug_log("debug.log");
Each source file that eventually #include
s logger.h will see this:
ofstream debug_log("debug.log");
and so create that object. Now you have multiple objects named debug_log
.
Forward declare the object here, but put the instantiation in a .cpp file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With