views:

349

answers:

3

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.

+3  A: 

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
+1  A: 

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.

anon
Ya thanks.........
yesraaj
+2  A: 

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