【问题标题】:Random problems with definition定义的随机问题
【发布时间】:2016-02-10 05:26:06
【问题描述】:

我正在尝试编译我的代码。编译器给出了关于“多重定义”的随机错误:

/tmp/cctnjqVc.o:(.bss+0x0): 'firstname'的多重定义
/tmp/ccPgFuZw.o:(.bss+0x0): 首先在这里定义
/tmp/cctnjqVc.o:(.bss+0x200): 'resultName[abi:cxx11]'的多重定义
/tmp/ccPgFuZw.o:(.bss+0x200): 这里先定义

我可以向您保证,我的代码中根本没有多重定义。 我的代码在多个文件中,所以如果你想全部查看:

http://www.github.com/calmunicorn/virtualsociety

但我认为有两个文件值得关注:

文件流.h

#ifndef FILESTREAM_H
#define FILESTREAM_H
#include <fstream>
#include <string>
#include <limits>
using namespace std;
static fstream logFile;
ofstream firstname;
void log(string argument);
string firstName_read(bool boyOrGirl);
string resultName;

#endif

文件流.cpp

#include "FileStream.h"
void log(string argument)
{
    logFile.open ("log.txt", fstream::out | fstream::app);

    logFile << argument;

    logFile.close();
}

string firstName_read (bool boyOrGirl)
{

    if (boyOrGirl == true)
         {
              firstname.open("Name/FirstName_Male.txt", fstream::in);
              firstname.close();
              return resultName;
         }
    else
         {
              firstname.open("Name/FirstName_Female.txt", fstream::in);
              firstname.close();
              return resultName;
         }
}

如果有什么不同,我会使用 Arch Linux。


编辑:

感谢您的所有回答,我做了所有被告知的事情,现在它可以正常工作了!

【问题讨论】:

  • 请注意,每个包含FileStream.h 的文件都有自己的独立logFile 变量——这可能不是您想要的。每个这样的文件还定义了全局变量firstnameresultname——这将导致“多重定义”问题。
  • 欢迎来到 Stack Overflow。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请参阅About 页面以及How do I ask questions here?What do I do when someone answers my question?

标签: c++ linux


【解决方案1】:

您通过在标题中定义(而不是仅仅声明)firstnameresultName 来实现 violate ODR。要声明它们,您需要做的是在头文件中将它们列为extern

extern ofstream firstname;
extern string resultName;

并且在.cpp 文件中有定义(没有extern)。

顺便说一句,headers should not use using namespace。相反,明确限定标题中的所有内容。

【讨论】:

    【解决方案2】:

    FileStream.h中的这一行

    ofstream firstname;
    

    将在每个包含 .h 的 .cpp 文件中定义一个变量 firstname

    您可能希望将其更改为 .h 中的 声明

    extern ofstream firstname;
    

    然后在其中一个 .cpp 文件中定义它

    ofstream firstname;
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2010-11-14
      相关资源
      最近更新 更多