0

I want to create a function outside the main.cpp file i've tried creating a header file but it doesn't work:

Main.cpp:

#include "other.h"
int main() {
    MyFunc();
}

Other.cpp

#include <iostream>
#include "other.h"
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

Other.h

#include <iostream>
#include "other.cpp"
void MyFunc();

nor CPP, G++, GCC compiler work

GCC Compiling error Errors shown by vs code

3 Answers3

1

You must include a header file and not a C++ file.

And therefore, you need to remove:

#include "other.cpp"

from other.h & use the following command-line for compiling:

g++ -o output main.cpp other.cpp

You'll get it linked and then compiled, then everything should be working fine.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • No, this is backwards. The implementation file should `#include` the header file; the header should not `#include` the implementation file. The problem here is misunderstanding the C++ compilation model. Each source file is separate, and gets compiled on its own. The resulting object files get linked and you have a program. You don't `#include` all your source files into one massive beast. – Pete Becker Jun 11 '20 at 21:54
  • @PeteBecker You're right. We must use `.h` or `.hpp` file, not a `cpp` in `#include`. – Rohan Bari Jun 12 '20 at 04:38
  • Much better! +1. – Pete Becker Jun 12 '20 at 12:37
0

You must remove #include "other.cpp" in header file.

-1

erase the line "#include "other.cpp" in your other.h and you will be fine...

Edit: you also need a header guard...

Huy Pham
  • 483
  • 5
  • 12