What are conventions for headers and cpp files in C ++?

In C ++, what is the convention for including headers for class files in the "main" file. eg.

myclass.h 

class MyClass {
  doSomething();
}


myclass.cpp

  doSomething() {
      cout << "doing something";
  }


run.cpp

#include "myclass.h"
#include "myclass.cpp"

etc..

Is this relatively standard?

+3
source share
6 answers

You do not include the .cpp file, but only the .h file. Function definitions in .cpp will be compiled into .obj files, which will then be linked to the final binary. If you include the .cpp file in other .cpp files, you will get two different .obj files with the same funciton definition, which will result in a linker error.

+3
source

. C .

+1

.cpp , . , . , file.o file.obj, , , . ,

Translation Unit 1 = run.cpp: myclass.h ...
Translation Unit 2 = myclass.cpp: myclass.h ...

. . , . , , . , . , :

Executable = mystuff: run.o myclass.o ...
+1

.cpp .o .o's

, myclass.cpp myclass.h .

0

You compile cpp files separately. If you include a cpp file in two or more cpp files, yoy may run into a conflict during the bind phase.

0
source

You do not include one * .cpp inside another * .cpp. Instead of this:


myclass.h

class MyClass {
  doSomething();
}

myclass.cpp

#include "myclass.h"

MyClass::doSomething() {
      cout << "doing something";
}

run.cpp

#include "myclass.h"

etc..

Instead of including myclass.cpp inside main.cpp (so that the compiler sees both of them in one pass), you compile myclass.cpp and main.cpp separately, and then let the linker combine them into a single executable.

0
source

Source: https://habr.com/ru/post/1703074/


All Articles