Sanjay Mishra
Sanjay Mishra

Reputation: 147

multiple definition of #define function

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?

Upvotes: 4

Views: 664

Answers (2)

Marco A.
Marco A.

Reputation: 43662

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");

Upvotes: 4

Matthew Moss
Matthew Moss

Reputation: 1248

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.

Upvotes: 3

Related Questions