Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple definition of #define function

Tags:

c++

c

g++

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?

like image 974
Sanjay Mishra Avatar asked Mar 17 '23 01:03

Sanjay Mishra


2 Answers

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");
like image 183
Marco A. Avatar answered Mar 23 '23 07:03

Marco A.


Each source file that eventually #includes 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.

like image 31
Matthew Moss Avatar answered Mar 23 '23 06:03

Matthew Moss