cloud
cloud

Reputation: 527

link error, how it happens?

i have two files, utility.h and utility.cpp. i declare a struct BoundingSphere in the .h file

struct BoundingSphere
{
    BoundingSphere();
    D3DXVECTOR3 _center;
    float _radius;
};
BoundingSphere::BoundingSphere()
{
    _radius = 0;
}

if i put the BoundingSphere::BoundingSphere() implementation into the .h file, i get a link error, error LNK2005: "public: __thiscall BoundingSphere::BoundingSphere(void)" already defined in bounding.obj

but, if i put the implementation into .cpp file, it works ok. my question is that how it could happen?

Upvotes: 1

Views: 69

Answers (2)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143081

Als tells the truth (not the whole truth, though), but to answer your question: if you put the implementation into .h file, then you have it in object files compiled from each source that includes the header. Therefore, you have multiple definitions. If you put it into .cpp file, then it is defined only once in that file.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206528

This happens because your first code example breaks the One Definition Rule.

When you include the definition in the header file the precompiler merely copy pastes the content of the header in every translation unit where you include the header.
What you end up with is multiple definitions of the same function, this breaks the One Definition rule and hence the linker error.

If you need to add definitions in the header file then you need to mark the function as inline. Though you should note that request to inline a function is merely a suggestion to the compiler and it is free to accept or reject it.

Upvotes: 3

Related Questions