multiple definition of a function

廉价感情. 提交于 2021-01-27 06:53:50

问题


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:

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 ?


回答1:


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.

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



回答2:


If you include that header into more than one .c file, each of them will define the function. That is what the error says.

What you should do is to only declare the function in the header (i.e. only put the prototype there; which you always should) and then define it in a single .c file (i.e. put the body in the .c file), encapsulated into the same switches as the prototype.

Header to be changed to this:

/* ... as you quoted ... */
    void _show_in_debug(const char *_file, unsigned int _line,
        const char *_function, const char *_msg);
/* ... rest of what you quoted ... */

Code file to contain this:

#incude <stdio.h>
#include "Yourheader.h"

#ifdef  NDEBUG
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



回答3:


I assume the file header file that you have presented is included in several source files. Why is this a problem? That is because you have defined your _show_in_debug() function in the header instead of declaring it in the header and defining it in a source file file. This leads to the function be defined in multiple source files that have included your header.

See http://www.cprogramming.com/declare_vs_define.html for more details (especially, see the "Common Cases" section).



来源:https://stackoverflow.com/questions/44789458/multiple-definition-of-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!