Reputation: 1
I'm trying to separate classes to different cpp files.
my files are:
Source.h:
#pragma once
#include "stdafx.h"
#include <iostream>
class printData {
public:
void print(int i);
void print(double f);
void print(char* c);
};
Source.cpp:
#include "stdafx.h"
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
ConsoleApplication3.cpp:
#include "stdafx.h"
#include <iostream>
#include "Source.h"
using namespace std;
int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
But when i try to build to project i'm getting :
1>ConsoleApplication3.obj : error LNK2019: unresolved external symbol "public: void __thiscall printData::print(int)" (?print@printData@@QAEXH@Z) referenced in function _main
1>ConsoleApplication3.obj : error LNK2019: unresolved external symbol "public: void __thiscall printData::print(double)" (?print@printData@@QAEXN@Z) referenced in function _main
1>ConsoleApplication3.obj : error LNK2019: unresolved external symbol "public: void __thiscall printData::print(char *)" (?print@printData@@QAEXPAD@Z) referenced in function _main
If i will combine all the files to just ConsoleApplication3.cpp there will be no error.
Upvotes: 0
Views: 61
Reputation: 2770
You've got two errors here:
In your .cpp file, you should define your methods as follows:
#include "stdafx.h"
#include <iostream>
#include "Source.h"
using namespace std;
void printData::print(int i) {
cout << "Printing int: " << i << endl;
}
void printData::print(double f) {
cout << "Printing float: " << f << endl;
}
void printData::print(char* c) {
cout << "Printing character: " << c << endl;
}
Don't write this class printData etc. in .cpp file as it is another definition of the class defined in Source.h. You should only define the class methods themselves in the .cpp file in the way shown above.
The compiler complains because all the main.cpp file sees is a Source.h file, which has a class that is only declared, not defined, as Source.cpp doesn't include Source.h. But even if you did include Source.h in Source.cpp, you would get a class redefintion error for the reason given above.
Upvotes: 1