0

While reading about compilation in C, got stuck understanding header files. I've googled my best but still confused. Please explain:

  1. If we have a main program (main.c), which calls for a certain function, and an additional program (mod.c), which contains the implementation of that function, what's the point of making an extra header file (mod.h)? I'm aware that it contains description of that function (and presumably many other functions) but still ... what's the point? Why can't I just prepare an objective file (mod.o) in advance and keep it handy for any of my programs to use when needed?
  2. How this #include "mod.h" works? The compiler sees the file, checks description of the function inside and ... what's next? How does it know where to find the function source code? Does it read the mod.c file and copy-pastes it to the main.c file?
  3. Where is the source code of standard functions like printf, scanf etc. in the Linux OS?

I'm sorry if my questions sound dumb.

  • Compiled code ("`.o` files") contains essentially no type information in C. Not even the number of arguments a function expects. It is not sufficient information to (try to) make sure you're using the functions in a correct way. – Mat Mar 17 '20 at 19:50
  • For you last question: look at the C library (usually glibc on Linux, but there are others). – Mat Mar 17 '20 at 19:51
  • Also when you #include, the pre-processor basically copy/pastes the contents of the file into your .c. That way, when the compiler runs, everything is ready for everything. – yhyrcanus Mar 17 '20 at 19:52
  • You don't seem to have a clear understanding of how compilers work. Your questions don't sound dumb but they may be difficult to answer, because there is a lot that you don't know. Luckily, there's a lot of good information on the internet. Maybe, you should do some reading. You could start with a search for "how do compilers work" for example. – Stuart Mar 17 '20 at 19:58
  • @Stuart, you're right, I guess I need to get deeper into the topic. –  Mar 17 '20 at 21:09
  • Thank you, Mat and yhyrcanus –  Mar 17 '20 at 21:09
  • 1
    Keep in mind that C is a product of the early 1970s. C compilers tend to only work on one source file at a time - they're not looking at other files in the directory, except for the files you specify in the `#include` directive in the source code. The contents of the included file are read in, so any type definitions, object or function declarations, etc., are now visible to the compiler. The code for library functions like `printf` is usually distributed as a pre-compiled library that you simply link against, although some implementations also distribute the source. – John Bode Mar 17 '20 at 23:19

0 Answers0