Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error lnk2005 already defined in .obj

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?

like image 274
zakjma Avatar asked May 28 '15 09:05

zakjma


1 Answers

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)
        {
            .......
        }
    }  
}
like image 126
Vlad from Moscow Avatar answered Nov 09 '22 11:11

Vlad from Moscow