Question with C ++ heading

I tested C ++ code while working with classes, and this question arose for me, and it made a little fun.

I created a header file that contains the definition of my class and a cpp file that contains the implementation.

If I use this class in another cpp file, then why am I including the header file instead of the cpp file that contains the class implementations?

If I include a class implementation file, then the class header file should be automatically imported (since I already included the header file in the implementation file)? Isn't that natural?

Sorry if this is a stupid question, I am sincerely interested in finding out why most people include .h instead of .cpp files when the latter seems more natural (I know a bit of python, maybe why this seems natural to me at least) . Is this historical or is there a technical reason related to the organization of the program or perhaps something else?

+3
source share
3 answers

, , ++ . ( ), , #define d "" , , , . .cpp , .

, , foo.h

int foo(int a, float b);

foo.cpp

#include "foo.h"
int foo(int a, float b) { /* implementation */ }

bar.cpp

#include "foo.h"
int bar(void) {
    int c = foo(1, 2.1);
}

foo.cpp, foo.o, bar.cpp bar.o. , , , foo() foo.cpp foo() bar.cpp (.. int a float int). , , , .cpp, , .

foo() bar.o. call foo. , bar.o, foo.cpp. , ( ), foo(), call foo a call 0x109d9829 ( , , foo() ).

, , foo() ( foo.o) foo() (in bar.o) - , , foo() int a float! ​​ ( , ++), , , . , .

+13

. .cpp . . , , , , .

.cpp, , , , , , .

+1

. , 10 (, -). .cpp 10 (.. , 2 1 ).

- . , , 10 . , , .h( ). , , .cpp(), , , . .h, , , .

For each body of the method, it is your choice whether to put it in a .h file or in a .cpp file. If it is in the .h file, the compiler can embed it when called, which can make the code a little faster. But compilation will be slower, and temporary .o (.obj) files may become larger (because each of them will contain the body of the compiled method), and the binary program file (.exe) may become larger, because the function body takes up space how many times he is nested.

0
source

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


All Articles