Dikshant Adhikari
Dikshant Adhikari

Reputation: 662

Why is my header implementation not working?

I am trying to get a feel for declaring functions in headers and implementing them on a separate file.

I have a main class from where I can instantiate World:

#include "World.cc"
#include <iostream>

using namespace std;

int main() {
    World say;
    say.hello();
return 0;
}

I keep getting an error stating:

"multiple definition of `World::hello()'"

Upvotes: 1

Views: 279

Answers (2)

Toby Speight
Toby Speight

Reputation: 30928

You want to have the declarations in the header file, and the implementation separate. The client code (main in your case) only needs the declarations, so it should include the header:

#include "World.h"

Preprocessor includes are very simple; it's little more than replacing the #include line with the contents of the file it names. When you included the source file World.cc, you caused the definitions to be built with your main.o object file. Then, when you link main.o with World.o, they both contain definitions for the functions of World.cc.

Upvotes: 2

StephenG
StephenG

Reputation: 2881

You need to include this is the main.cpp

#include "HelloWorld.h"

not the HeloWorld.cc file.

Upvotes: 5

Related Questions