6

Non inline function defined in header file with guards

#if !defined(HEADER_RANDOM_H)
#define HEADER_RANDOM_H 
void foo()
{
//something
}
#endif

Results in linker error : Already defined in someother.obj file Making the function inline works fine but I am not able to understand why the function is already erroring out in first case.

yesraaj
  • 46,370
  • 69
  • 194
  • 251

3 Answers3

12

If the header is included in more than one source file and the function is not marked as "inline" you will have more than one definition. The include guards only prevent multiple inclusions in the same source file.

  • 1
    I would also underline that the `inline` keyword is not necessary when speaking about classes methods defined inside the class declaration http://stackoverflow.com/a/145952/2436175 – Antonio Feb 14 '14 at 13:54
8

You're violating the one definition rule. If you want to define a function directly in the header, you must mark it as inline -- that will allow the function to be defined multiple times. Also note that inline has no other meaning, particularly it doesn't force the compiler to inline calls (contrary to popular belief).

avakar
  • 32,009
  • 9
  • 68
  • 103
4

Since it is not inline, each translation unit will have its own copy of the function resulting in the function being defined multiple times.

Naveen
  • 74,600
  • 47
  • 176
  • 233