Multiple Definition of <'variable/function'>

I am trying to write a basic program with a candidate.h file, a candidate.cpp file, and a main.cpp file

I declared a function void readCandidates() in my candidate.h file.

I then define it in candidate.cpp as
1
2
3
4
5
6
7
8
9
10
11
12
void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

  for (int i = 0; i < nCandidates; ++i)
    {
      getline (cin, candidateNames[i]);
      delegatesWon[i] = 0;
    }
}


The variables nCandidates, candidateNames[] and delegatesWon[] are all declared in candidate.h as well.

I also have
1
2
3
4
#ifndef CANDIDATE_H
#def CANDIDATE_H
...
#endif 

in my candidate.h file to ensure that it doesn't get defined twice.

When I run the command make main I get the error
1
2
3
4
5
6
7
8
9
/home/pmurray/cs250/Asst1/primaries.cpp:33: multiple definition of `candidate'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:8: first defined here
primaries.o: In function `assignDelegatesToCandidates()':
/home/pmurray/cs250/Asst1/primaries.cpp:37: multiple definition of `nCandidates'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:15: first defined here
primaries.o: In function `assignDelegatesToCandidates()':
/home/pmurray/cs250/Asst1/primaries.cpp:38: multiple definition of `delegatesWon'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:16: first defined here
candidates.o: In function `readCandidates()':


I tried putting extern before the declaration of one of the variables, and that resulted in the error
1
2
3
4
5
candidates.cpp:(.text+0x49): undefined reference to `candidateNames'
primaries.o: In function `findCandidate(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
primaries.cpp:(.text+0x120): undefined reference to `candidateNames'
primaries.o: In function `printCandidateReport(int)':
primaries.cpp:(.text+0x1d8): undefined reference to `candidateNames' 


Anyone know what I am doing wrong?
Last edited on
Sounds like you have some variables declared in your .h file. You'll need to define them in one cpp file, and then use extern in all other cpp files.
so extern precedes the variable name everwhere? or just in candidate.cpp or main.cpp?
extern should proceed the variable names in all .cpp files except for one of them (any of them are fine)
you could use extern in the .h
Topic archived. No new replies allowed.