-2

Is there a need to create a header file after making a source file? What are the things included in a header file? is it necessary or is it good for only source files containing a function definition?

I'm really confused since what you put in header files, such as function portotypes, can also be placed in a source file. Are header files only good for declaring global variables? Is creating a header file with the same name as your source file necessary.

I already got the answer of "What are header files for". Apparently a lot of questions similar to this have been posted that's why adding some follow up questions.

mc8
  • 315
  • 7
  • 21
  • 1
    You claim to know C but don't understand what header files are for? Really? – Fred Larson Jun 25 '13 at 16:21
  • If you mean create with the word make, for re-use and seperation of code into functional units. I.e sound handling stuff and video handling stuff should be seperate units. The .c files contain the meat of the code, the .h files tell code in other c/h files how to make use of the meat. Things included in the header file are things that are relevant to the source code whose functions it declares. Try asking google "what are .h files for?" – enhzflep Jun 25 '13 at 16:25
  • Sorry, I have previous a knowledge on programming c++. And I just studied C just now. But I don't know all the extra stuffs. :D – mc8 Jun 25 '13 at 16:35
  • @enhzflep thank you for your answer. I was not sure if I should create a header file for all of my source codes. But I'm guessing I should. thanks :) – mc8 Jun 25 '13 at 16:40

1 Answers1

3

I guess you could search on Google and find whatever your need to know but to make it short:

In C (and C++), every source (.c or .cpp) file is compiled on its own translation unit. This means that every file is compiled on its own to produce an object file. Once all object files are compiled, they are linked together to create your final binary file.

This means that a source file has no clue of what's defined in other source files, the header file is needed to fill this gap: it provides the declarations of variables, functions and whatever that are implemented in one or many source files, so that, when you are including it inside another source file, the compiler can verify that all these external things are correctly used. This is not its only purpose, it can aid in other taks (like reuse of code or partitioning) but this is why it exists.

The header file is literally included when you use the #include directive.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • must I create a binary file? I read a post on the Internet that after creating a header file you can create the binary file – mc8 Jun 25 '13 at 17:38