Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including headers and Main.h [closed]

Ok not sure if this is the right way or even a correct way but i have seen this and started to use it, Say you have 6 files

main.cpp
main.h

car.cpp
car.h

speed.cpp
speed.h
  • 1st - should you ever have a main.h?
  • 2nd - if main.h has #include car.h and #include speed.h then in car/speed.cpp do you just have to add #main.h (thus it would include car/speed.h)
  • 3rd - should you ever go that route?
like image 602
Glen Morse Avatar asked Jun 26 '13 08:06

Glen Morse


People also ask

Do you need main h?

It is not typical to have a "main. h" - but there's certainly no rule that forbids it. As to what needs to be included, and how you achieve that, really depends on what the respective classes do, what knowledge of each other they need.

Do you include header or CPP in Main?

In general, you should only include headers in . h files that are needed by those headers. In other words, if types are used in a header and declared elsewhere, those headers should be included. Otherwise, always include headers only in .

Do header files have to end in H?

h suffix is used by header files that are provided with the operating system; however, the suffix is not required for user-generated header files. Note: Several of the header files provided with the operating system end with . inc (include file). Additional header files are provided with the operating system.


2 Answers

#include minimalistically. The reason behind an include should be that, if removed, the code doesn't compile.

Don't #include when you can forward-declare. If "Class A;" will suffice, don't #include a.h.

In particular, prefer to forward-declare in header files, avoiding nested includes which generate highly coupled mega-include files.

See also Self-sufficient header files, in a related question.

like image 70
Daniel Daranas Avatar answered Oct 04 '22 00:10

Daniel Daranas


1) Only if you need to expose something in main.cpp to other cpp files, so depends on what it has.

2) Possible but not recommended.

3) For a number of reasons (code design, compile time, etc), you want to include as little as needed. Additionally, its convention for your class to have a .h and a .cpp and for one to directly include the other. You should also try to include headers in your .cpp files, and try to avoid headers including headers where possible.

like image 44
Karthik T Avatar answered Oct 04 '22 02:10

Karthik T