Множественное определение <'variable / function'> - PullRequest
2 голосов
/ 07 сентября 2011

Я пытаюсь написать базовую программу с файлом candid.h, файлом candid.cpp и файлом main.cpp

Я объявил функцию void readCandidates() в моем файле кандидата.h.

Затем я определяю его вандидате.cpp как

void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

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

Все переменные nCandidates, candidateNames[] and delegatesWon[] также объявлены в кандидате.

У меня также есть

#ifndef CANDIDATE_H
#def CANDIDATE_H
...
#endif 

в моем файле candid.h, чтобы он не определялся дважды.

Когда я запускаю команду make main, я получаю сообщение об ошибке

/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()':

Я попытался поместить extern перед объявлением одной из переменных, и это привело к ошибке

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' 

Кто-нибудь знает, что я делаю неправильно?

sources.cpp

#include <iostream>

using namespace std;
#include "candidates.h"

void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

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

sources.h

#ifndef CANDIDATES_H
#define CANDIDATES_H

#include <iostream>
#include <string>

using namespace std;

// Max # of candidates permitted by this program
extern const int maxCandidates = 10;

// Names of the candidates participating in this state's primary
extern string candidate[maxCandidates];

// Names of all candidates participating in the national election
extern std::string candidateNames[maxCandidates];

// How many candidates in the national election?
extern int nCandidates;

// How many delgates have been won by each candidate
extern int delegatesWon[maxCandidates];

extern int findCandidate (std::string name);


/**
 * read the list of candidate names, initializing their delegate counts to 0.
 */
void readCandidates ();

#endif // CANDIDATES_H

primaries.cpp (который является моим main.cpp)

#include <iostream>
//#include "candidates.cpp"

using namespace std;

#include "candidates.h"

// How many delegates are assigned to the state being processed
int delegatesForThisState;

// How many candidates in the primary for the state being processed
int nCandidatesInPrimary;

// How many states participate in the election
int nStates;

// How many delegates in the election (over all states)
int totalDelegates = 0;

// How many votes were cast in the primary for this state
int totalVotes;

// How many votes wone by each candiate in this state's primary
int votesForCandidate[maxCandidates];


/**
 * For the most recently read primary, determine how many delegates have
 * been won by each candidate.
 */
int assignDelegatesToCandidates ()
{
  int remainingDelegates = delegatesForThisState;
  for (int i = 0; i < nCandidatesInPrimary; ++i)
    {
      int candidateNum = findCandidate(candidate[i]);
      int nDel = (delegatesForThisState * votesForCandidate[i] + (totalVotes-1)) / totalVotes;
      if (nDel > remainingDelegates)
    nDel = remainingDelegates;
      delegatesWon[candidateNum] += nDel;
      remainingDelegates -= nDel;
    }
}



/**
 * Find the candidate with the indicated name. Returns the array index
 * for the candidate if found, nCandidates if it cannot be found.
 */
int findCandidate (std::string name)
{
  int result = nCandidates;
  for (int i = 0; i < nCandidates && result == nCandidates; ++i)
    if (candidateNames[i] == name)
      result = i;
  return result;
}


/**
 * Print the report line for the indicated candidate
 */
int printCandidateReport (int candidateNum)
{
  int requiredToWin = (2 * totalDelegates + 2) / 3; // Note: the +2 rounds up
  if (delegatesWon[candidateNum] >= requiredToWin)
    cout << "* ";
  else
    cout << "  ";
  cout << delegatesWon[candidateNum] << " " << candidateNames[candidateNum] << endl;
}



/**
 * read the info on one state's primaries
 */
void readState ()
{
  totalVotes = 0;
  cin >> nCandidatesInPrimary >> delegatesForThisState;
  totalDelegates += delegatesForThisState;  // "x += y" is a shorthand for "x = x + y"
  string word, line;
  getline (cin, line);
  for (int i = 0; i < nCandidatesInPrimary; ++i)
    {
      cin >> votesForCandidate[i];
      totalVotes = totalVotes + votesForCandidate[i];

      cin >> word;
      getline (cin, line);
      candidate[i] = word + line;
    }
}



/**
 * Generate the report on the national primary election.
 */
int main(int argc, char** argv)
{
  readCandidates();
  int nStates;
  cin >> nStates;
  for (int i = 0; i < nStates; ++i)
    {
      readState();
      assignDelegatesToCandidates();
    }
  for (int i = 0; i < nCandidates; ++i)
    {
      printCandidateReport(i);
    }
  return 0;
}

1 Ответ

3 голосов
/ 07 сентября 2011

Вы объявляете переменные и функции extern в заголовочном файле, вам все равно нужно их где-то определить, лучшее в файле .cpp, где вы их используете (candidates.cpp в вашем случае).

Добавьте в ваш файл candidates.cpp определения всех тех переменных, которые вы используете в своих функциях, которые решат вашу проблему.

Кстати, согласился, что это не очень хорошая форма программирования, но, вероятно, это за пределамио объеме этого вопроса.Вам не нужны глобальные переменные, потому что к ним не нужно обращаться за пределами файла реализации (.cpp).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...