user3176017
user3176017

Reputation: 103

Duplicate Symbol error from clang/llvm compiler

While working tonight on a project, I struggled for a while with a linker error that complained about a "duplicate symbol".

I eventually figured out that I had a helper function defined instead of just declared in my header file and this was the source of the problem (lost over an hour chasing this).

why can I define inline functions in my header like this;

int get_val const {return r;}

but the same definition outside the class throws a linker error?

Upvotes: 2

Views: 1316

Answers (2)

user3193161
user3193161

Reputation: 1

If you needed a inline function, you should define it in a header file. You can see C++ Primer(4th edtion), which has some pages about inline function. I think you can get your answer there.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227608

In-class member function definitions are implicitly marked inline, whereas non-member ones are not, so, if your definition is in a header file, you break the one-definition-rule (ODR) as soon as more than one translation unit includes your header. inline provides a means to get around this.

So you need to explicitly mark your non-member function as inline:

inline int foo() {return 42;}

Alternatively, only declare it in the header and define it in a .cpp file.

See this related post on inline functions.

Upvotes: 3

Related Questions