ABC
ABC

Reputation: 591

Classes and headers in C++

Why Xcode gives me "Redefinition of Console" error? Should not be the same name in the header and cpp ?

Here is the code:

ui.cpp:

#include "ui.h"
    class Console {
    public:
    void run() {
        puts("Hello my friend!");

    }
};

ui.h:

class Console {
public:
    void run();
};

main.cpp:

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

int main(int argc, const char * argv[]) {
    Console c;
    c.run();
return 0;
}

Upvotes: 1

Views: 827

Answers (3)

Nate
Nate

Reputation: 19030

Classes are defined in header files. The .cpp should contain the implementation of the functions, not the class definition.

ui.cpp should be:

#include <stdio.h>    /* for puts */
#include "ui.h"

void Console::run() {
    puts("Hello my friend!");
}

If you’re learning C++, try a tutorial like http://www.learncpp.com/.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564441

Should not be the same name in the header and cpp?

No, the .cpp file should have the implementations, not the declaration. This would look like:

#include "ui.h"

void Console::run() {
    puts("Hello my friend!");
}

Note that you also probably should include guards in your .h file to prevent them from being included multiple times.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Because you redefined it. Literally right there in your code.

To define one of its member functions, you do just that, without repeating the class's definition:

#include "ui.h"

void Console::run()
{
   puts("Hello my friend!");
}

Upvotes: 0

Related Questions