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?

  • Please provide the error message you are getting. But in any case, *never* include `.cpp` files in other files. – walnut Mar 25 '20 at 03: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? – nick Mar 25 '20 at 03: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 `#include`d (not vice versa). – JaMiT Mar 25 '20 at 04:00

1 Answers1

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;
}
Zem
  • 464
  • 3
  • 14
  • 3
    "*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. – walnut Mar 25 '20 at 04:03
  • 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? – Zem Mar 25 '20 at 04:11
  • I think this link will helpful. http://www.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. – Zem Mar 25 '20 at 04:14
  • Yes, basically, that is very likely OP's issue. – walnut Mar 25 '20 at 04:21