0

I have searched almost every website I could, but nobody has been able to answer my question. Basically what I ask, is what exactly should I place in a header file? I know of function declarations, but are variable declarations in a .h file also a thing? I need to know what the "tradition" or the "usual method" is of usage of header files.

EDIT : If this helps, I just recently started C++ and my objective with learning this language is an opportunity to get into the industry, mainly gamedev, and I need to know what the proper way of doing stuff is. Hence the question.

cheemse
  • 41
  • 6
  • 2
    Your book should explain how to use header files. – Asteroids With Wings Nov 11 '20 at 16:08
  • 4
    If you're just starting, and you want to get into the industry, and you want to do gamedev, stop searching random websites and start learning by properly studying [a proper book](https://stackoverflow.com/q/388242/4386278). – Asteroids With Wings Nov 11 '20 at 16:11
  • 1
    I can find many websites that discuss what goes into header files, including [elsewhere on StackOverflow](https://stackoverflow.com/questions/1945846/what-should-go-into-an-h-file). Not sure where you looked. – Nathan Pierson Nov 11 '20 at 16:13
  • @AsteroidsWithWings i understand that the best way to learn is using a book, but i am still in school and it is extremely hectic. although once things become a little easy, i do intend to pick one up. thamks – cheemse Nov 11 '20 at 16:14
  • @shreksleafgreenpp Like anything, you'll get out what you put in. Nothing worth doing is "easy". :) – Asteroids With Wings Nov 11 '20 at 16:22

1 Answers1

2

Header files conventionally contain declarations of entities that you wish to share between translation units.

That usually means class definitions, type aliases, and function declarations.

A translation unit, very roughly speaking, is "a .cpp file".

So, if you use a function in a.cpp, and you also use it in b.cpp, a declaration for it needs to be available in both translation units, and the best way to do that is to write it once in a header file, then include the header file in both .cpp files.

That's it.

While it's possible to declare variables in a header file, it's rare to do so. For starters, you'd want to put extern on it to make it not a definition (you don't want multiple definitions!). At that point, you have to ask yourself why you're not using a class.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35