Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple definition of a function

Tags:

c++

macros

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 ?

like image 510
apramc Avatar asked Jan 31 '23 03:01

apramc


1 Answers

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);
}
like image 126
dbush Avatar answered Feb 03 '23 14:02

dbush