Maya Archambault
Maya Archambault

Reputation: 11

Random problems with definition

I am trying to compile my code. The compiler is giving random errors about 'multiple definition':

/tmp/cctnjqVc.o:(.bss+0x0): multiple definition of 'firstname'
/tmp/ccPgFuZw.o:(.bss+0x0): first defined here
/tmp/cctnjqVc.o:(.bss+0x200): multiple definition of 'resultName[abi:cxx11]'
/tmp/ccPgFuZw.o:(.bss+0x200): first defined here

I can assure you that there is no multiple definition at all in my code. My code is in multiple files so if you want to see them all:

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

but there are two files that I think are concerned:

FileStream.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

FileStream.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;
         }
}

I'm on Arch Linux if makes any difference.


edit :

Thank you for all the answer i did everything i was told to and now it work without any problems!

Upvotes: 1

Views: 789

Answers (2)

dxiv
dxiv

Reputation: 17638

This line in FileStream.h

ofstream firstname;

will define a variable firstname in each .cpp file that includes the .h.

You probably want to change that to a declaration in the .h

extern ofstream firstname;

then define it in just one of the .cpp files

ofstream firstname;

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223043

You did violate ODR by defining (as opposed to just declaring) firstname and resultName in the header. What you need to do, to declare them, is to list them as extern in the header file:

extern ofstream firstname;
extern string resultName;

and have the definition (without extern) in the .cpp file.

BTW, headers should not use using namespace. Explicitly qualify everything in your header, instead.

Upvotes: 2

Related Questions