LINK : ~~~\CSC 161-6ren">
gpt4 book ai didi

c++ - 为什么我在声明 ifstream 时收到 "Already defined"错误?

转载 作者:太空狗 更新时间:2023-10-29 20:05:16 25 4
gpt4 key购买 nike

我不熟悉使用头文件之类的东西,上学期我们在一个巨大的(可怕的 :p)文件中做了所有事情......

我是否在做不该做的事情?尝试运行该程序会产生以下结果:

1>  LINK : ~~~\CSC 161\Accounting Assignment\Debug\Accounting Assignment.exe not found or not built by the last incremental link; performing full link
1>driver.obj : error LNK2005: "class std::basic_ifstream<char,struct std::char_traits<char> > welcomeFile" (?welcomeFile@@3V?$basic_ifstream@DU?$char_traits@D@std@@@std@@A) already defined in statistics.obj
1>~~~~\CSC 161\Accounting Assignment\Debug\Accounting Assignment.exe : fatal error LNK1169: one or more multiply defined symbols found
1>

统计.h:

#ifndef _STATISTICS_INTERFACE_
#define _STATISTICS_INTERFACE_
...
#include<fstream>

using namespace std;
ifstream welcomeFile; //if I comment this out, it compiles

class Stats
{
...blah...
};

void welcome();
void pause();
void printFile(ifstream &inFile);

#endif

统计.cpp:

#include "statistics.h"

...working functions...

void welcome()
{
system("CLS");
welcomeFile.open("about.txt");
printFile(welcomeFile);
welcomeFile.close();
pause();
}

错误看起来像是某个东西试图被定义两次,但我认为 #ifndef 应该设置它以便它只定义尚未定义的东西?这是我声明 welcomeFile 的唯一地方......

最佳答案

因为你在头文件中定义了对象,违反了一个定义规则

永远不要在头文件中定义对象!

header 保护防止 header 的内容多次包含在相同 translation unit 在预处理过程中。它们不会阻止内容包含在不同的翻译单元中。当您将此头文件包含在不同的翻译单元中时,这些单元中的每一个都会有此对象的定义。
编译器分别编译每个翻译单元以生成一个单独的目标文件 (.o),每个 .o 文件都将具有此目标定义的拷贝。当链接器在生成 .exe 时尝试链接到对象/符号名称时,它会发现同一对象/符号的多个定义,从而导致不知道要链接到哪个。为避免此问题,标准定义了一个称为 One defintion rule(ODR) 的规则。 ,禁止同一实体的多个定义。
如您所见,在头文件中包含对象定义并在多个翻译单元中包含该头文件违反了 ODR。

如果你想使用一个全局对象,你需要将它声明为extern,并在一个且唯一的源文件中定义它。

好读:
error LNK2005, already defined?

关于c++ - 为什么我在声明 ifstream 时收到 "Already defined"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14516123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com