TheWaterProgrammer
TheWaterProgrammer

Reputation: 8259

C++ Linker error with a function definition outside class

Its such a weird error with my C++ code.

I want to maintain a header file with some methods. Lets call it Util.hpp. I have the below simple method in it.

bool CheckVal(int value) {

  if (value == 1)
    return true;
  else
    return false;    
}

I include Util.hpp in another class's cpp & invoke the method. I end up with a linker error saying

:-1: error: 3 duplicate symbols for architecture x86_64

I am building this with clang on osx.

How can I get rid of this error ? what is so wrong in what I am doing ?

I am having the error in spite of inlining the function. really strange !

Upvotes: 2

Views: 1729

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

If you keep free function definitions in a header file you must make them with the inline keyword:

   inline bool CheckVal(int value) {       
// ^^^^^^
      return value == 1;
   }

Otherwise the function definition appears in every translation unit that includes the header file, and the linker sees multiple definitions of it.


Also as I did above you don't need if/else for retuning bool values.


Another solution is to just declare the function in the header

bool CheckVal(int value);

and move the implementation (definition) to a separate translation unit.
That has at least the advantage that any dependend translation units on that header won't need to be recompiled, if you change something in the implementation.

Upvotes: 3

eerorika
eerorika

Reputation: 238411

what is so wrong in what I am doing ?

The one definition rule requires that a (non inline) function must be defined exactly once.

If you include your header in multiple translation units, then there will be multiple definitions, thus odr is violated.

If there are multiple - different definitions for the function, that also violates odr.

How can I get rid of this error ?

Solution 1: Do not define the function in a header. Instead define it in a source file. Source files are not included in other source files, so there should be exactly one definition when you use this approach.

Solution A: Declare the function inline.

In both cases, check that there are no other functions by the same name.


Only if the function is odr-used. This subtlety is not relevant to this question.

Upvotes: 1

Related Questions