Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 多个定义,已在此处定义_C++_Visual C++ - Fatal编程技术网

C++ 多个定义,已在此处定义

C++ 多个定义,已在此处定义,c++,visual-c++,C++,Visual C++,我有三个简单的文件。 “banana.cc” namespace ocr{ int a = 5; } “apple.cc” “main.cc” 编译器插入所有#include后,main.cc如下所示: namespace ocr{ int a = 5; } namespace ocr{ int b = a; } int main() { return 0; } 为什么这会导致重新定义? 谢谢。因为您正在项目中编译apple.cc、banana.cc和

我有三个简单的文件。 “banana.cc”

namespace ocr{
    int a = 5;
}
“apple.cc”

“main.cc”

编译器插入所有#include后,main.cc如下所示:

namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

int main()
{
    return 0;
}


为什么这会导致重新定义?
谢谢。

因为您正在项目中编译apple.cc、banana.cc和main.cc

因此,您正在编译此文件:

namespace ocr{
    int a = 5;
}
namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}
namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

int main()
{
    return 0;
}
以及此文件:

namespace ocr{
    int a = 5;
}
namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}
namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

int main()
{
    return 0;
}
以及此文件:

namespace ocr{
    int a = 5;
}
namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}
namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

int main()
{
    return 0;
}

显然,
ocr::a
在所有三个文件中都有定义,而
ocr::b
在其中两个文件中有定义。

没有足够的声誉发表评论,但我只想对此进行详细说明,以防仍然存在混淆

如果要在文件之间共享一些变量,请创建一个头文件并在其中声明它。 i、 e

然后在编译main.cc时,将其链接到apple.cc和banana.cc,而不是“包括”它

g++main.cc apple.cc banana.cc-o输出


请注意,您不能在全局范围内单独声明和初始化,这就是为什么您可能需要使用上述setter函数(initApple()等)。或者在头文件中使用extern并在源文件中定义它。

您不应该包含
.cc
文件。我假设这些文件是您的项目的一部分/已经作为可执行文件的一部分生成。您是否在
Visual Studio
下交叉编译
linux
代码?我正在试图找出
Visual c++ OCR:A/<代码>在BANANA.OBJ中,另一个在Apple。Objt中,还有一个在Maul.Obj.Obj.我不认为是IDE。我怀疑OP已经把文件添加到项目中,而<代码>包含了< /代码> d。相对长度单位。