函数的多重定义 [英] multiple definition of a function
问题描述
我定义了一个函数,当调试标志在头文件中关闭时显示一条消息,如下所示:
I defined a function to show a message when debug flags are off in a header file as below:
#ifdef NDEBUG
#define debug_msg(expr, msg) (static_cast<void>(0))
#else /* Not NDEBUG. */
#ifndef SHOW_DEBUG_H_
#define SHOW_DEBUG_H_
#include <stdio.h>
void _show_in_debug(const char *_file, unsigned int _line,
const char *_function, const char *_msg)
{
printf("%s\t%d\t%s\t%s\n", _file, _line, _function, _msg);
fflush(NULL);
}
#endif
#define debug_msg(expr, msg) \
((expr) \
? _show_in_debug(__FILE__, __LINE__, __func__, msg) \
: static_cast<void>(0))
#endif
当我在文件中包含头文件时,出现以下错误:
when I include the header in more than a file, I get the following error:
_show_in_debug(char const *,unsigned int,charconst *,char const *)'
multiple definition of `_show_in_debug(char const*, unsigned int, char const*, char const*)'
我不完全知道自己在做什么错,有什么帮助吗?
I don't exactly know what I am doing wrong here, any help ?
推荐答案
即使有了包含保护,您最终在每个编译单元中的定义仍为 show_in_debug
.然后,将这些单元链接起来会导致多定义错误.
Even with the include guards, you end up with a definition of _show_in_debug
in each compilation unit. Linking those units then results to a multiple definition error.
对于这样的调试功能,请将功能定义为 static
,以使其在其编译单元之外不可见:
For a debugging function like this, define the function as static
so that it is not visible outside its compilation unit:
static void _show_in_debug(const char *_file, unsigned int _line,
const char *_function, const char *_msg)
{
printf("%s\t%d\t%s\t%s\n", _file, _line, _function, _msg);
fflush(NULL);
}
这篇关于函数的多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!