Multiple declaration of function C++ [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have to refactor a project and thought of separating the sources and header files. It worked great for the "Empregado" class, but when I tried to replicate it to the "Engenheiro" class I got the multiple declaration error
A screenshot of the error I'm getting when trying to build the project
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj): In function `ZNK10Engenheiro7getNomeB5cxx11Ev':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:5: multiple definition of `Engenheiro::getNome[abi:cxx11]() const'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Engenheiro.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:5: first defined here
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj): In function `ZN10Engenheiro7setNomeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:9: multiple definition of `Engenheiro::setNome(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Engenheiro.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:9: first defined here
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj): In function `ZNK10Engenheiro11getProjetosEv':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:13: multiple definition of `Engenheiro::getProjetos() const'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Engenheiro.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:13: first defined here
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj): In function `ZN10Engenheiro11setProjetosEi':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:17: multiple definition of `Engenheiro::setProjetos(int)'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Engenheiro.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Engenheiro.cpp:17: first defined here
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Vendedor.cpp.obj): In function `ZN8Vendedor7setNomeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Vendedor.cpp:5: multiple definition of `Vendedor::setNome(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Vendedor.cpp:5: first defined here
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Vendedor.cpp.obj): In function `ZNK8Vendedor7getNomeB5cxx11Ev':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Vendedor.cpp:9: multiple definition of `Vendedor::getNome[abi:cxx11]() const'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Vendedor.cpp:9: first defined here
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(Vendedor.cpp.obj): In function `ZN8Vendedor15quotaTotalAnualEv':
D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Vendedor.cpp:13: multiple definition of `Vendedor::quotaTotalAnual()'
CMakeFiles\exercicio_revisao_refatoracao.dir/objects.a(main.cpp.obj):D:/UFMG/UFMG-DCC204/CPP/Modulo3/exercicio-revisao-refatoracao/Vendedor.cpp:13: first defined here
collect2.exe: error: ld returned 1 exit status
I have uploaded all the files to GitHub https://github.com/jvbraganca/exercicio-revisao-refatoracao/tree/multiple-declaration-error
The header and source file for Engenheiro are here:
Engenheiro.h
#ifndef ENGENHEIRO_H
#define ENGENHEIRO_H
#include <string>
#include "Empregado.h"
class Engenheiro : public Empregado {
public:
const std::string &getNome() const;
void setNome(const std::string &nome);
int getProjetos() const;
void setProjetos(int projetos);
private:
std::string nome;
int projetos;
};
#endif //ENGENHEIRO_H
Engenheiro.cpp
#include "Empregado.h"
void Empregado::setHorasTrabalhadas(double horasTrabalhadas) {
Empregado::horasTrabalhadas = horasTrabalhadas;
}
void Empregado::setSalarioHora(double salarioHora) {
Empregado::salarioHora = salarioHora;
}
void Empregado::setQuotaMensalVendas(double quotaMensalVendas) {
Empregado::quotaMensalVendas = quotaMensalVendas;
}
double Empregado::getHorasTrabalhadas() const {
return horasTrabalhadas;
}
double Empregado::getSalarioHora() const {
return salarioHora;
}
double Empregado::getQuotaMensalVendas() const {
return quotaMensalVendas;
}
double Empregado::getPagamentoMes() const {
double horasTrabalhadas = getHorasTrabalhadas();
/**
* Calcula as horas extras trabalhadas, bônus de 50% se
* tiver mais que 8 horas extras trabalhadas.
*/
if (horasTrabalhadas > MAX_HORAS_TRABALHADAS) {
double x = horasTrabalhadas - MAX_HORAS_TRABALHADAS;
horasTrabalhadas += x / 2;
}
return horasTrabalhadas * salarioHora;
}
void Empregado::printInfo(const std::string &nome, double salario, int projetosOuQuota, int tipoFuncionario) {
if (tipoFuncionario == 1) {
std::cout << "Nome: " << nome << std::endl;
std::cout << "Salario Mes: " << salario << std::endl;
std::cout << "Projetos: " << projetosOuQuota << std::endl;
std::cout << std::endl;
} else if (tipoFuncionario == 2) {
std::cout << "Nome: " << nome << std::endl;
std::cout << "Salario Mes: " << salario << std::endl;
std::cout << "Quota vendas: " << projetosOuQuota << std::endl;
std::cout << std::endl;
} else {
throw "Tipo de funcionário não reconhecido!";
}
}
Empregado::~Empregado() = default;
I can't see where I am declaring it multiple times. Maybe it is a dummy question
Any help is welcome, thanks!
Solved: I was importing the source file instead of the header file on main.cpp

As was mentioned in main.cpp you are including source files.
#include "Engenheiro.cpp"
#include "Vendedor.cpp"
You should include the corresponding header files instead.
#include "Engenheiro.h"
#include "Vendedor.h
This fixes the problem:
1>------ Rebuild All started: Project: ZERO_CHECK, Configuration: Debug x64 ------
1>Checking Build System
2>------ Rebuild All started: Project: exercicio_revisao_refatoracao, Configuration: Debug x64 ------
2>Building Custom Rule C:/Users/juanr/Downloads/exercicio-revisao-refatoracao/CMakeLists.txt
2>Empregado.cpp
2>Engenheiro.cpp
2>main.cpp
2>Vendedor.cpp
2>Generating Code...
2>exercicio_revisao_refatoracao.vcxproj -> C:\Users\juanr\Downloads\exercicio-revisao-refatoracao\build\Debug\exercicio_revisao_refatoracao.exe
========== Rebuild All: 2 succeeded, 0 failed, 0 skipped ==========

Related

I keep getting the error the error: clang: error: linker command failed with exit code 1 (use -v to see invocation). Please help and Thank You [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 2 years ago.
I am somewhat new to C++ and and when I try to run the following code
main.cpp:
#include <iomanip>
#include <string>
#include <limits>
#include "console.h"
using namespace std;
double calculate_future_value(double monthly_investment, double yearly_interest_rate, int years);
int main()
{
cout << "The Future Value Calculator\n\n";
char choice = 'y';
while (tolower(choice) == 'y')
{
cout << "INPUT\n";
double monthly_investment =
console::get_double("Monthly Investment: ", 0, 10000);
double yearly_rate =
console::get_double("Yearly Interest Rate: ", 0, 30);
int years =
console::get_int("Years ", 0, 100);
cout << endl;
double future_value = calculate_future_value(monthly_investment,
yearly_rate, years);
cout << "OUTPUT\n"
<< fixed << setprecision(2)
<< "Monthly Investment: " << monthly_investment << "\n"
<< fixed << setprecision(1)
<< "Yearly Interest Rate: " << yearly_rate << "\n"
<< "Years: " << future_value << "\n\n"
<< "Future Value: " << future_value << "\n\n";
choice = console::get_char("Continue? (y/n): ");
}
cout << "Bye!\n\n";
}
double calculate_future_value(double monthly_investment, double yearly_interest_rate, int years)
{
double monthly_rate = yearly_interest_rate / 12 / 100;
int months = years * 12;
double future_value = 0;
for (int i = 0; i < months; ++i)
{
future_value = (future_value + monthly_investment) *
(i + monthly_rate);
}
return future_value;
}
and
console.h:
#define PANDA_CONSOLE_H
#include <string>
#include <limits>
namespace console
{
double get_double(std::string prompt,
double min = std::numeric_limits<double>::min(),
double max = std::numeric_limits<double>::max());
int get_int(std::string prompt,
int min = std::numeric_limits<int>::min(),
int max = std::numeric_limits<int>::max());
char get_char(std::string prompt,
bool add_blank_line = true);
}
#endif
I would get the following error
Undefined symbols for architecture x86_64:
"console::get_double(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, double, double)", referenced from:
_main in main-f6ee4e.o
"console::get_int(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, int, int)", referenced from:
_main in main-f6ee4e.o
"console::get_char(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool)", referenced from:
_main in main-f6ee4e.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I've tried moving the definition of calculate_future_value() after using namespace std; and before double calculate_future_value(double monthly_investment, double yearly_interest_rate, int years); and because that didn't work, I am now confused to what I need to do. Please help. Thank You!
Where you are confused is in the difference between the function declaration and the function definition. In your file console.h you define the namespace console and you declare the functions:
#ifndef PANDA_CONSOLE_H
#include <string>
#include <limits>
namespace console
{
double get_double(std::string prompt,
double min = std::numeric_limits<double>::min(),
double max = std::numeric_limits<double>::max());
int get_int(std::string prompt,
int min = std::numeric_limits<int>::min(),
int max = std::numeric_limits<int>::max());
char get_char(std::string prompt,
bool add_blank_line = true);
}
#endif
(note: your header-guard should be #ifndef PANDA_CONSOLE_H so that if PANDA_CONSOLE_H is NOT yet defined, the following information is included. [but good job on thinking to include a header-guard to prevent multiple inclusions of the function declarations if you include console.h in more than one source file])
For every function Declaration -- there must be a corresponding function Definition
When you declare a function, you are simply telling the compile that a function with this name (symbol) will be defined later -- but you make that function available from the point of the declaration forward in that source file.
When you define the function, the compiler reserves space for it and provides the address for where the compiled code for that function be found. During linking, any time that function is used in your source files, it will resolve to the address where the compiled code for that function actually resides.
If you declare the function, but fail to define the function, then when the linker attempts to locate the code that goes with the declaration, it can't find it and will issue the error similar to:
Undefined symbols for (insert missing function name here)
In your case you need to write a console.cpp that contains the definition for each of the functions you declare in consile.h. For example (and this is only an example with no effort made to have the functions exactly match what you do with them in main()), you could write the following console.cpp to define each of the function, e.g.
#include "console.h"
#include <iostream>
double console::get_double(std::string prompt, double min, double max)
{
double value = 0;
std::cout << prompt;
if (!(std::cin >> value)) {
std::cerr << "error: invalid double value or EOF.\n";
return 0;
}
if (value < min || max < value) {
std::cerr << "error: value out of range.\n";
return 0;
}
return value;
}
int console::get_int(std::string prompt, int min, int max)
{
int value = 0;
std::cout << prompt;
if (!(std::cin >> value)) {
std::cerr << "error: invalid integer value or EOF.\n";
return 0;
}
if (value < min || max < value) {
std::cerr << "error: value out of range.\n";
return 0;
}
return value;
}
char console::get_char(std::string prompt, bool add_blank_line)
{
char value = 0;
std::cout << prompt;
if (!(std::cin >> value)) {
std::cerr << "error: EOF or unrecoverable error\n";
return 0;
}
if (add_blank_line)
std::cout.put('\n');
return value;
}
(note: I #include <iostream> in console.cpp just for the std::cin, std::cout and std::cerr calls)
Compile
You can then compile your project with:
$ g++ -Wall -Wextra -pedantic -Wshadow -std=c++11 -Ofast console.cpp -o main main.cpp
or
$ clang++ -Wall -Wextra -pedantic -Wshadow -std=c++11 -Ofast console.cpp -o main main.cpp
Then your can run your ./main program (which produces very wrong output based on my made-up function definitions)
Example Use/Output
$ ./main
The Future Value Calculator
INPUT
Monthly Investment: 123.45
Yearly Interest Rate: 12.4
Years 4
OUTPUT
Monthly Investment: 123.45
Yearly Interest Rate: 12.4
Years: 90457540156111170020897362009600300274844235338297210119913472.0
Future Value: 90457540156111170020897362009600300274844235338297210119913472.0
Continue? (y/n): n
Bye!
Note: I suggestion you change the yearly_rate to years in OUTPUT so the years are shown correctly:
<< "Years: " << years << "\n\n"
The point being, that for every function declaration there must be a corresponding function definition to allow the linker to match the symbol used in your code with the actual code for that function. Let me know if that fills in the missing pieces, and if not, I'm happy to help further.
(if you stand behind the payout calculated by your program, I have $123.45 to invest)

C++ multiple definition of function in class definition

I just got into C++ and I was trying to write a simple code for a simulation, but I bumped into a multiple definition problem than I cannot solve.
So, I'm creating a class and this is the header file:
Piano.h
#ifndef PIANO_H
#define PIANO_H
#include"vettore.h"
#include"PuntoMat.h"
#include<string>
#include<vector>
class Piano
{
public:
//Costruttori
Piano(std::string material, float lenght, float inclin = 0)
: m_material(material), m_lenght(lenght), m_inclin(inclin), m_time(0) {;}
//Metodo per l'aggiunta di corpi al piano
void Add(PuntoMat p) { m_corpi.push_back(&p); }
//Metodo che stampa le coordinate dei corpi nel sistema
void Print();
private:
std::string m_material;
std::vector<PuntoMat*> m_corpi;
float m_lenght;
float m_inclin;
float m_time;
};
#endif
this is the corresponding file .cxx, where I define the function "Print"
Piano.cxx
#include"vettore.h"
#include"PuntoMat.h"
#include"Piano.h"
#include<iostream>
#include<stdlib.h>
#include<vector>
void Piano::Print()
{ std::cout << "Tempo: " << m_time << " s" << std::endl;
if(m_corpi.size() == 0)
{ std::cout << "Nessun corpo sul piano" << std::endl;
exit(1);
}
for(int i=0; i<m_corpi.size(); i++)
{ std::cout << *m_corpi[i] << std::endl;
}
std::cout << std::endl;
}
This is the code I'm using to validate the class
main.cxx
#include<iostream>
#include"vettore.h"
#include"PuntoMat.h"
#include"Piano.cxx"
#include<string>
main()
{
PuntoMat a(3, Vettore( 0, 0), Vettore( 5.4, 0), "Legno");
PuntoMat b(5, Vettore( 8.3, 6.5), Vettore( 0, 0), "Vetro");
Piano p( "Ferro", 50);
p.Add(a);
p.Add(b);
p.Print();
return 0;
}
When I compile I get a multiple definition error about the function Print, this one:
/tmp/ccp1giKM.o: In function `Piano::Stampa()':
main.cxx:(.text+0x0): multiple definition of `Piano::Stampa()'
/tmp/cctCJRQF.o:Piano.cxx:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
I really don't know how to solve this problem, since it seems to me that the function Print() has been defined only in the file Piano.cxx. Can anyone help me with this?
P.s. Ignore the general meaning of the code and the comments (they are in italian). All the other classes included have been already validate and there is no problem with them.
Your problem is that you try to include the cxx file. You should only include .h/.hpp files. Instead of include the source files you should tell your compiler to use it.
So in your case removing the "#include"Piano.cxx" line and than calling your compiler in this way(asuming g++),
g++ main.cxx Piano.cxx
should fix the problem. If you want to create bigger projects you should have a look at creating object files from your sources.

visual c++ error C3867

I've had a lot of problems with this code and i've fixed most of them but i dont know whats wrong here.
1>------ Build started: Project: molar mass, Configuration: Debug Win32 ------
1> Source.cpp
1>c:\users\heliz_000\documents\visual studio 2013\projects\molar mass\molar mass\source.cpp(54): error C3867: 'std::basic_ifstream<char,std::char_traits<char>>::close': function call missing argument list; use '&std::basic_ifstream<char,std::char_traits<char>>::close' to create a pointer to member
1>c:\users\heliz_000\documents\visual studio 2013\projects\molar mass\molar mass\source.cpp(55): error C3867: 'std::basic_ofstream<char,std::char_traits<char>>::close': function call missing argument list; use '&std::basic_ofstream<char,std::char_traits<char>>::close' to create a pointer to member
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
That is the build output for visual studio 2013
#include <iostream>
#include <iomanip>
#include <fstream>
#include <Windows.h>
using std::basic_ofstream;//Thought it would help
using namespace std;
using std::basic_ifstream;//Thought it would help
using std::char_traits;//Thought it would help
/**
* Author: Alex M.
* Date: 3/12/2015
* Desc: Calculates the molar
* mass of compounds,
* elements and
* substances.
*/
void nor();
void tut();
void calc();
int i;
double m;
ifstream inFile;//Is this how to do if/ofstream?
ofstream outFile;
int main()
{
char ele;
bool a;
a = true;
if (i<1)
tut();
nor();
while (a = true)
{
cout << "Enter your compound or type 'Help': ";
cin >> ele;
calc();
while (ele != '\n')//This part is unfinished but seems to work
{
}
}
system("pause");
}
void nor()//This is where i think the problem is
{
inFile.open("runs.dat");
outFile.open("runs.dat");
inFile >> i;
i++;
outFile << i;
inFile.close;
outFile.close;
}
void tut()
{
cout << "Enter your equation with each " << endl << "element seperated by a space." << endl;
cout << "Example: HCl -> H Cl" << endl;
cout << "If theres more than one ion of each " << endl << "element per equation, enter that " << endl << "ion as many time as it appears." << endl;
cout << "Example: NaSO4 -> Na S O O O O" << endl;
system("pause");
}
I've already looked all over forums but no one else seems to be having my problem.
I commented all over the code with where i think the problem is.
I'm very new to C so please don't judge my simplistic coding skills.
In the error message where it says:
source.cpp(54)
source.cpp(55)
that means those errors are on line 54 and 55 respectively. You'll find that those lines are:
inFile.close;
outFile.close;
You probably meant to call those functions:
inFile.close();
outFile.close();
It's an error to mention the name of a member function in that way if you are not calling the function (and function calls require parentheses).
However, a better design would be to make inFile and outFile be local objects inside the function where you are using them. Then the files will automatically be closed when those objects go out of scope.

Pass an object by reference to a method

I think the mistake i'm doing it's so stupid but i don't know what i'm doing wrong.
I have a class with static and non-static vars and some methods, all public.
In my program i want to create an object and pass this object to a general method by reference.
The program doesn't compile and the compiler throws really weird error messages.
Undefined symbols for architecture x86_64: "prueba::num", referenced
from:
_main in ccbRZYqe.o
metodoC(prueba*) in ccbRZYqe.o
prueba::prueba()in ccbRZYqe.o
prueba::inicio() in ccbRZYqe.o "prueba::flag", referenced from:
metodoC(prueba*) in ccbRZYqe.o
prueba::prueba()in ccbRZYqe.o
prueba::inicio() in ccbRZYqe.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status
Code
#include <iostream>
using namespace std;
class prueba
{
private:
public:
static bool flag;
static int num;
float complejo;
// Metodos
//--------------
prueba()
{
flag = false;
num = 0;
complejo = 0.0;
}
void inicio()
{
flag = true;
num = 5;
complejo = 3.2;
}
bool cambio()
{
flag++;
num++;
complejo++;
}
};
bool metodoC(prueba* ensayo)
{
cout << "-----------------------------------------" << endl;
cout << "- flag: " << ensayo->flag << endl;
cout << "- num: " << ensayo->num << endl;
cout << "- Complejo: " << ensayo->complejo << endl;
cout << "-----------------------------------------" << endl;
return true;
}
//-----------------------------------
// M A I N
//-----------------------------------
int main(int argc, char *argv[])
{
prueba test;
test.inicio();
test.num += 2;
test.complejo += 5.2;
metodoC( &test );
return 0;
}
You need to define your static members. They are only declared.
class prueba {
// as before
};
and in the implementation file:
bool prueba::flag=false;
int prueba::num=0;
Note that you shouldn't put the definitions in a header because you will get a definition of the statics for each translation unit. You need to put them in an implementation file that is then used to make a single object file that clients can build against.
Be careful though, each time you instantiate a new prueba object, you reset the static members in the constructor.
static members in class should be declared inside the class but define outside the class
`bool prueba::flag=false;`
int prueba::num=0;`
add these after class and remove their defination from inside the constructor .
It will work fine for you
I think the error is because the num value in prueba is declared as static, hence accessing it by: test.num will not work, and this is why the value is undefined.
If you change that to prueba::num += 2; it should work ok, also add in the appropriate initializers:
bool prueba::flag = false;
int prueba::num = 0;

Undefined symbols for architecture x86_64. what's wrong with my codes?

devices.h file
#ifndef DEVICES_H
#define DEVICES_H
class malfunctionRecord
{
private:
int Num_Malfunction_Detection;
int Type_Malfunction;
int Last_Malfunction;
public:
malfunctionRecord();
void malfunction(int mlfn,int tm);
void display();
int getRecord(int*m,int*t);
};
class device
{
private:
char *Name;
malfunctionRecord malfunctionRec;
int Serial_Num;
int Value_Device;
public:
device(char*n,int sn);
~device();
void display();
void recordMalfunction(int m,int t);
int getMalfunctionRecord(int *m,int *t);
int amIThisDevice(char*n);
};
#endif
(this is my devices.cpp file)
#include<iostream>
#include "devices.h"
using namespace std;
malfunctionRecord::malfunctionRecord()
{
Num_Malfunction_Detection=0;
Last_Malfunction=0;
Type_Malfunction=='No_Malfunction';
}
void malfunctionRecord::malfunction(int mlfn,int tm)
{
Num_Malfunction_Detection=Num_Malfunction_Detection+mlfn;
Last_Malfunction=Last_Malfunction+tm;
}
void malfunctionRecord::display()
{
if (Num_Malfunction_Detection=0)
cout<<" the device has never malfunctioned";
else
cout<<"The device has malfunctioned"<<Num_Malfunction_Detection<<"times. the malfunction is type"<<Type_Malfunction<<" and last malfunction time is"<<Last_Malfunction<<endl;
}
int malfunctionRecord::getRecord(int*m,int*t)
{
cout<<"The device has malfunctioned"<<Num_Malfunction_Detection<<"times.";
Type_Malfunction=*m;
Last_Malfunction=*t;
}
/*int device::device(char*n,int sn)
{
}
void device::display()
{
}
void device::recordMalfunction(int m,int t)
{
}
int device::getMalfunctionRecord(int *m,int *t)
{
}
int device::amIThisDevice(char*n)
{
}
*/
(this is my main cpp file, given)
#include "definitions.h"
#include "devices.h"
#include <iostream>
using namespace std;
int main() {
malfunctionRecord m1, m2;
device d1("Turn Signal Lever", 195), d2("Accelerator", 247), *d3;
int c, m, t; // Temp variables to hold values retrieved from getRecord.
char ch; // Used to hold display until user presses enter.
// malfunctionReport tests.
cout << "Initially both m1 and m2 should have no malfunctions:\n\n";
m1.display();
cout << "\n";
m2.display();
cout << "\n";
// Set a malfunction in m1.
m1.malfunction(MALFUNCTION_UNDER_RANGE,10);
cout << "m1 should now have one malfunction with time 10 and under range.\n";
m1.display();
// Now add some malfunctions and verify that only the last is kept.
m1.malfunction(MALFUNCTION_OVER_RANGE,25);
cout << "\nm1 should now have two malfunctions, the last one with time 25 and over range.\n";
m1.display();
m1.malfunction(MALFUNCTION_STOPPED_WORKING,32);
cout << "\nm1 should now have three malfunctions, the last one with time 32 and stopped working.\n";
m1.display();
// Now test the retrieval function.
c = m1.getRecord(&m, &t);
cout << "\n\nValues returned from getRecord are " << c << ", " << m << ", and " << t << ".\n";
cout << "\nEnd of malfunctionReport tests.\n\n\n";
// Hold display so user has a chance to check results so far.
cout << "Press ENTR when ready to continue:";
ch = cin.get();
// device class tests.
cout << "\n\n\nBeginning tests for device class.\n";
cout << "Display original d1 and d2:\n\n";
d1.display();
cout << "\n";
d2.display();
cout << "\n\nTest the amIThisDevice function. \n";
if(d1.amIThisDevice("Turn Signal Lever")) cout << " First test on d1 passed.\n";
else cout << " First test on d1 failed.\n";
if(d1.amIThisDevice("Accelerator")==0) cout << " Second test on d1 passed.\n";
else cout << " Second test on d1 failed.\n";
cout << "\n\nNow test record and get malfunction function members.\n";
d1.recordMalfunction(MALFUNCTION_UNDER_RANGE,25);
cout << " Should see count equal 1 and under range malfunction at time 25:\n";
d1.display();
d1.recordMalfunction(MALFUNCTION_OVER_RANGE,50);
cout << "\n Should see count equal 2 and over range malfunction at time 50:\n";
d1.display();
d1.recordMalfunction(MALFUNCTION_STOPPED_WORKING,64);
cout << "\n Should see count equal 3 and stopped working malfunction at time 64:\n";
d1.display();
cout << "\n\nTry to retrieve malfunction report. Should see same values as above.\n";
c = d1.getMalfunctionRecord(&m,&t);
cout << "Values returned from getRecord are " << c << ", " << m << ", and " << t << ".\n";
// Test destructor. Create a new device and then delete it.
cout << "\n\nTesting create and destroy n object. If you don't see the";
cout << "\nend of tests message, there is something wrong with your destructor.\n\n";
d3 = new device("Temporary Device", 100);
d3->display();
delete d3;
cout << "\n\nEnd of tests for Program 3.\n";
return 0;
}
(this is my definition.h file)
#define NO_MALFUNCTION 20
#define MALFUNCTION_OVER_RANGE 21
#define MALFUNCTION_UNDER_RANGE 22
#define MALFUNCTION_STOPPED_WORKING 23
when I compile it, I keep getting these error:
g++ devices.cpp main.cpp -o a
devices.cpp:9:23: warning: character constant too long for its type
main.cpp: In function ‘int main()’:
main.cpp:11: warning: deprecated conversion from string constant to ‘char*’
main.cpp:11: warning: deprecated conversion from string constant to ‘char*’
main.cpp:53: warning: deprecated conversion from string constant to ‘char*’
main.cpp:56: warning: deprecated conversion from string constant to ‘char*’
main.cpp:76: warning: deprecated conversion from string constant to ‘char*’
Undefined symbols for architecture x86_64:
"device::device(char*, int)", referenced from:
_main in cc7F618W.o
"device::display()", referenced from:
_main in cc7F618W.o
"device::amIThisDevice(char*)", referenced from:
_main in cc7F618W.o
"device::recordMalfunction(int, int)", referenced from:
_main in cc7F618W.o
"device::getMalfunctionRecord(int*, int*)", referenced from:
_main in cc7F618W.o
"device::~device()", referenced from:
_main in cc7F618W.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
can anyone tell me what's wrong with my codes? thanks!
You commented out a bunch of function definitions in devices.cpp (the five at the bottom). They're still in the header.
This is the linker complaining about you informing it of a symbol, and then not defining it.
Either define the functions or remove all the references to them.