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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would also underline that the inline keyword is not necessary when speaking about classes methods defined inside the class declaration stackoverflow.com/a/145952/2436175
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).

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.