You have your file structure wrong.
Non-defining declarations belong in a header file (.h
or .hpp
ending by convention):
// HelloWorld.h
// No standard library headers required, because you don't use anything from `std::`
class HelloWorld{
public:
void printHelloWorld();
};
(Non-inline) definitions belong in a source file (.cpp
or .cxx
or .cc
by convention):
// HelloWorld.cpp
#include "HelloWorld.h"
#include <iostream>
// #include<string> is not needed, since you don't use `std::string` here
void HelloWorld::printHelloWorld() {
std::cout << "This is the world" << std::endl;
}
and source files should not be included in other files. Only the header files with the declarations should be included:
#include "HelloWorld.h"
int main(){
HelloWorld helloWorld;
helloWorld.printHelloWorld();
return 0;
}
Each source file is by convention compiled as individual translation unit and there may be a definition for a (non-inline) function in only one of the translation units.
#include
does essentially nothing more than copy-paste the code from the other file into the files using it. So if you include the .cpp
with a definition in another .cpp
file, then both translation units for the two .cpp
files will contain the definition, violating the one-definition-rule mentioned above.
Your error is telling you that you have the definition for HelloWorld::printHelloWorld()
(which is not inline) in two translation units.