7

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
zakjma
  • 2,030
  • 12
  • 40
  • 81
  • possible duplicate of [error LNK2005: already defined - C++](http://stackoverflow.com/questions/622229/error-lnk2005-already-defined-c) – Timo May 28 '15 at 10:50

1 Answers1

13

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)
        {
            .......
        }
    }  
}
Timo
  • 2,212
  • 2
  • 25
  • 46
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    Do you know why the include guard does not work for this case? – Timo May 28 '15 at 09:31
  • 1
    @Timo It works. Simply there are two separate compilation units each of them includes the header. – Vlad from Moscow May 28 '15 at 09:35
  • Reading up on the subject, it appears that `static` is also an option. Found an explanation here: http://forums.codeguru.com/showthread.php?285375-inline-function-vs-static-function – Timo May 28 '15 at 09:42
  • @Timo It depands on whether you want that this function would be static.:) – Vlad from Moscow May 28 '15 at 09:43
  • You're definitely right, but I felt that it was a good thing to mention this additional option. Making the function static also fixes this example, but it might not be the right solution in another project. – Timo May 28 '15 at 10:40
  • @Timo I did it as you are advising. – Vlad from Moscow May 28 '15 at 10:57