0

I'm trying learn c++ due to school work. Recently I've come up with a problem that stuck with me for a while. If there were 3 files, main.cpp, Fish.cpp, Fish.h

Fish.h:

#ifndef FISH_H
#define FISH_H

class Fish
{
    public:
        Fish();
};

#endif

Fish.cpp:

#include <iostream>
#include Fish.h
using namespace std;

Fish::Fish()
{
    cout << "I love fish" << endl;
}

main.cpp :

#include <iostream>
#include "Fish.cpp"
using namespace std;

int main(){
    Fish Salmon;
    return 0;
}

Here comes the problem, I know if I want to use the Fish() constructor in "main.cpp", I'm supposed to include Fish.h, and then compile all 3 files, but due to curiosity, I tried to include "Fish.cpp". If I include "Fish.cpp" to "main.cpp", then everything in Fish.cpp will get copied into main.cpp, which includes the line <#include Fish.h>, right? But why every time I compile and run, the terminal gives me errors?

3
  • Please provide the error message you are getting. But in any case, never include .cpp files in other files. Commented Mar 25, 2020 at 3:57
  • 1
    The syntax for #include Fish.h is not correct in Fish.cpp, it should be #include "Fish.h"; is that the error you're getting? Commented Mar 25, 2020 at 3:59
  • 1
    "then compile all 3 files" -- no, you have only two source files to compile. Source files (.cpp) get compiled. Header files (.h) get #included (not vice versa). Commented Mar 25, 2020 at 4:00

1 Answer 1

0

include header file, NOT cpp files.

Fish.cpp

#include <iostream>
#include "Fish.h" // change here
using namespace std;

Fish::Fish()
{
    cout << "I love fish" << endl;
}

main.cpp

#include <iostream>
#include "Fish.h" // change here
using namespace std;

int main(){
    Fish Salmon;
    return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

"I know [...] I'm supposed to include Fish.h, and then compile all 3 files, but due to curiosity, I tried to include "Fish.cpp"": OP knows that. That is not the question.
Thanks to help to understand question. Fish.cpp has Fish.h header include. So, if main.cpp can include Fish.cpp file, main.cpp includes Fish.h, Fish.cpp both, right?
I think this link will helpful. cplusplus.com/forum/general/39618. In here, Fish.cpp is actually being compiled twice, so there will be some problems. And, once the linker starts combining your object files, it picks up multiple definitions of whatever you had in Fish.cpp, and raises a few errors.
Yes, basically, that is very likely OP's issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.