2015-09-24 4 views
1

В попытке закодировать базовый класс «Банковская учетная запись», разделенный на заголовочный файл, и два .cpp-файла при попытке компиляции отображаются следующие сообщения об ошибках.Неопределенные символы для архитектуры x86_64 C++ class

(Развиваясь в Vim через терминал (OS X Yosemite 10.10.5))

Я не уверен, что сообщения об ошибках, имеют в виду ни то, как решить эту проблему. Заранее благодарим за понимание и отзывы.

Terminal Command Сообщения об ошибках &:

$ g++ -std=c++11 -Wall Account.cpp 

Error Message 01

$ g++ -std=c++11 -Wall test.cpp 

Error Message 02

Account.h

//Account.h 
//Account class definition. This file presents Account's public 
//interface without revealing the implementation of Account's member 
//functions, which are defined in Account.cpp. 

#ifndef ACCOUNT_H 
#define ACCOUNT_H 

#include <iostream> 

class Account 
{ 
    public: 
    Account(int amount); //constructor initialize accountBalance 
    void credit(int creditValue); //credits the account balance 
    void debit(int debitValue) ; //debits the account balance 
    int getBalance() const; //gets the account balance 

    private: 
    int accountBalance;//account balance for this Account 
};//end class Account 
#endif 

Account.cpp

//Account.cpp 
//Account member function definitions. This file contains 
//implementations of the member functions prototype in Account.h 
#include <iostream> 
#include "Account.h" //include definition of class Account 

using namespace std; 

//constructor initializes accountBalance with int supplied 
//as argument 
Account::Account(int amount) 
{ 
    if(amount >= 0) 
    { 
    accountBalance = amount; 
    } 
    else 
    { 
    accountBalance = 0; 
    cerr << "The initial balance was invalid" << endl; 
    } 
} 
//function to credit amount to account balance 
//value must be greater than zero 
void Account::credit(int creditValue) 
{ 
    if(creditValue > 0) 
    { 
    accountBalance += creditValue; 
    } 
    else 
    { 
    cout << "Credit value cannot be negative nor zero.\n"; 
    } 
} 
//function to debit amount from account balance 
//value cannot exceed current account balance 
void Account::debit(int debitValue) 
{ 
    if(accountBalance >= debitValue) 
    { 
    accountBalance -= debitValue; 
    } 
    else 
    { 
    cout << "Debit amount exceeds account balance.\n"; 
    } 
} 
//function to get the account balance 
int Account::getBalance() const 
{ 
    return accountBalance; 
} 

test.cpp

#include <iostream> 
using namespace std; 

// include definition of class Account from Account.h 
#include "Account.h" 

// function main begins program execution 
int main() 
{ 
    Account account1(50); // create Account object 
    Account account2(25); // create Account object 

    Account account3(-25); // attempt to initialize to negative amount; 

    // display initial balance of each object 
    cout << "account1 balance: $" << account1.getBalance() << endl; 
    cout << "account2 balance: $" << account2.getBalance() << endl; 

    int depositAmount; // stores deposit amount read from user 

    cout << "\nEnter deposit amount for account1: "; // prompt 
    cin >> depositAmount; // obtain user input 

    cout << "\ndeposit " << depositAmount 
     << " into account1 balance\n\n"; 
    account1.credit(depositAmount); // add to account 

return 0; // indicate successful termination 

} // end main 
+1

Вы должны использовать флаг '-c' с g ++ для создания объектных файлов из каждого из файлов' .cpp'. Например, 'g ++ -std = C++ 11 -c -Wall Account.cpp'. Затем свяжите их с exectuable. Без флага '-c' g ++ пытается создать исполняемый файл, используя только' Account.cpp', который не удался. Также см. [This] (http://stackoverflow.com/questions/3202136/using-g-to-compile-multiple-cpp-and-h-files). – crayzeewulf

+0

высоко оценили – aguilar

ответ

2

Проблема заключается в том, что вы собираете каждый файл .cpp, как если бы это был единственный файл в программе. Вместо этого вы должны использовать опцию -c для вашего компилятора C++ (при условии, что GCC или Clang) должны скомпилировать каждый .cpp-файл. Это даст вам соответствующий набор файлов .o (object). Затем связать их вместе с окончательным командной строки, как это:

g++ -o myprogname Account.o test.o 

Если вы используете инструмент сборки, как CMake, эти данные будут обрабатываться автоматически.

Смежные вопросы