.obj中已经定义的变量;这里发生了什么? [英] Variable already defined in .obj; What is going on here?

查看:166
本文介绍了.obj中已经定义的变量;这里发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

head.h


#pragma once

namespace foo
{
    int bar;

    int funct1();
}

head.cpp

#include "head.h"

int foo::funct1()
{
    return bar;
}

main.cpp

#include <iostream>

#include "head.h"


int main()
{
    foo::bar = 1;
    std::cout << foo::funct1() << std::endl;
    return 0;
}

在head.obj中已经定义的错误LNK2005"int foo :: bar"(?bar @ foo @@ 3HA)

Error LNK2005 "int foo::bar" (?bar@foo@@3HA) already defined in head.obj

我不知道发生了什么.我尝试寻找答案,但是每个人的问题都针对他们的代码,甚至都没有接近我所遇到的问题.

I don't understand what is going on. I tried looking for the answer but everyone's questions are so specific to their code and don't even look close to the problem that I am having.

我没有将.cpp文件包含到main中.我没有重新定义任何内容.我实际上只是将1分配给变量,然后在同一名称空间中使用函数将其返回.如何多次定义?

I am not including .cpp files into main. I am not redefining anything. I am literally just assigning 1 to the variable then returning it with a function in the same namespace. How is it being defined multiple times?

推荐答案

标头head.h包含在两个编译单元head.cppmain.cpp中.因此,变量bar被定义了两次.您可以按照以下方式声明没有定义的变量

The header head.h is included in two compilation units head.cpp and main.cpp. So the variable bar is defined twice. You could declare the variable without its definition the following way

#pragma once

namespace foo
{
    extern int bar;

    int funct1();
}

,然后在某些cpp模块中对其进行定义.

and then define it in some cpp module.

这篇关于.obj中已经定义的变量;这里发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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