Error lnk2005 already defined in .obj

zakjma picture zakjma · May 28, 2015 · Viewed 10.7k times · Source

There are many question about this error. But they are related to only a single variable.

test.h

namespace World
{
    enum Objects
    {
        TERRAIN = 1,
        BOX = 2,
        SPHERE = 4,
        CAPSULE = 8

    };  

    void WorldObjects2(unsigned int mask)
    {
      .......
    }
}

void test();

test.cpp

#include "test.h"

void test()
{
    .......
}

main.cpp

#include "test.h"
int main()
{
    test();
    return 0;
}

When I run these code on visual stduio 2013, it throws an error. It says that error LNK2005: "void __cdecl World::WorldObjects2(unsigned int)" (?WorldObjects2@World@@YAXI@Z) already defined in main.obj. How can I correct this error?

Answer

Vlad from Moscow picture Vlad from Moscow · May 28, 2015

Your project has two definitions of function WorldObjects2 : one is in the compilation unit test.cpp and other is in the compilation unit main.cpp because the header where the function is defined is included in these two cpp files.

Either use function specifier inline

inline void WorldObjects2(unsigned int mask)
{
    .......
}

Or move the function definition to some cpp file leaving only a function declaration (without its definition) in the header.

Another approach is to make the function as having the internal linkage. For example you could add keyword static

static void WorldObjects2(unsigned int mask)
{
    .......
}

or could place the function in an unnamed namespace within the given namespace.

namespace World
{
    // ...
    namespace
    {
        void WorldObjects2(unsigned int mask)
        {
            .......
        }
    }  
}