Question

I'm having some issues with compiling a program using a class inside of a header file. I believe that I set up the project and linker settings right, but it seems no matter what I try, it gives me an error. I've searched all over forums and i"m at my wit's end...

some background information: my IDE is code::blocks(for windows), and in the linker settings I've included "header.o" and "Main.o"

the code:

Main.cpp:

#include<iostream>
#include"Header.h"

using namespace std;

int main()
{

Pizza ob;

}

Header.h:

#ifndef HEADER_H
#define HEADER_H

class Pizza
{

public:

Pizza();

protected:
private:

};

#endif

header.cpp:

#include "Header.h"
#include <iostream>

using namespace std;

Pizza::Pizza()
{
cout << "linked!";
}

the errors I get when compiling:

obj\Debug\Header.o||In function `ZN5PizzaC2Ev':|
H:\New Build Target pro\Headertest\Header.cpp|6|multiple definition of `Pizza::Pizza()'|
obj\Debug\Header.o:H:\New Build Target pro\Headertest\Header.cpp|6|first defined here|
obj\Debug\Header.o||In function `ZN5PizzaC2Ev':|
H:\New Build Target pro\Headertest\Header.cpp|6|multiple definition of `Pizza::Pizza()'|
obj\Debug\Header.o:H:\New Build Target pro\Headertest\Header.cpp|6|first defined here|
obj\Debug\Main.o||In function `main':|
H:\New Build Target pro\Headertest\Main.cpp|8|multiple definition of `main'|
obj\Debug\Main.o:H:\New Build Target pro\Headertest\Main.cpp|8|first defined here|
||=== Build finished: 6 errors, 0 warnings (0 minutes, 7 seconds) ===|

That's just about all I've done with it. I've searched these errors and came up with just about nothing. Please help, if there's any more information I should include, please ask me About it.

Was it helpful?

Solution

in the linker settings I've included "header.o" and "Main.o"

Don't. It's been a while since I've used Code::Blocks, but generally every IDE in existence will automatically set up the linker line based on the source files that are being compiled, and chances are Code::Blocks already includes "header.o" and "Main.o" for you.

If you've explicitly added those two object files, you've effectively added them twice to the link line, and the linker sees that the symbols are defined twice and complains.

Let the IDE do the work there, you don't have to explicitly specify object files. (And, for the most part, in general, the default settings when you start a new project should be enough to at least get you off the ground.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top