错误lnk2005已在.obj中定义 [英] Error lnk2005 already defined in .obj

查看:349
本文介绍了错误lnk2005已在.obj中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个错误有很多问题。但它们只与一个变量相关。



test.h

 命名空间世界
{
enum对象
{
TERRAIN = 1,
BOX = 2,
SPHERE = 4 ,
CAPSULE = 8

};

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

测试();

test.cpp


$ b b

  #includetest.h

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

main.cpp

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



当我在visual stduio 2013上运行这些代码时,会抛出一个错误。它说明在main.obj 中已经定义的错误LNK2005:void __cdecl World :: WorldObjects2(unsigned int)(?WorldObjects2 @ World @@ YAXI @ Z)。

你的项目有两个函数定义 WorldObjects2 :一个是在编译单元 test.cpp 和其他是在编译单元 main.cpp 因为



使用函数说明符 inline

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

或者将函数定义移动到某个cpp文件,只留下一个函数声明



另一种方法是使函数具有内部链接。例如你可以添加关键字static

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

或者可以将函数放在未命名的命名空间给定命名空间。

 命名空间世界
{
// ...
命名空间
{
void WorldObjects2(unsigned int mask)
{
.......
}
}
}


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?

解决方案

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)
        {
            .......
        }
    }  
}

这篇关于错误lnk2005已在.obj中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆