[英]multiple definition of #define function
I have logger.h file and defining a macro function for logging: 我有logger.h文件并定义了一个用于记录的宏函数:
//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. 此头文件包含在多个c文件中。 and using log() function.
并使用log()函数。 g++ is giving:
g ++给出:
/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 如果你在项目级(或多个翻译单元)声明了
LOG_DEBUG
,他们都会看到
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 一个cpp文件
ofstream debug_log("debug.log");
Each source file that eventually #include
s logger.h will see this: 最终
#include
s logger.h的每个源文件都会看到:
ofstream debug_log("debug.log");
and so create that object. 所以创建该对象。 Now you have multiple objects named
debug_log
. 现在您有多个名为
debug_log
对象。
Forward declare the object here, but put the instantiation in a .cpp file. Forward在此声明对象,但将实例化放在.cpp文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.