Why do some people write methods in header file ?
And what’s the difference between writing a method in a procedure file and a header file?
Here’s the code :
Work.h
#include <time.h>
void DoWork(int n)
{
clock_t t = clock() + n * CLOCKS_PER_SEC / 1000;
while(clock() < t);
}
Program.c
#include <stdio.h>
#include "work.h"
int main(void)
{
printf("Starting work\n");
DoWork(100);
printf("Work has finished\n");
}
Is there any difference between writing a method in a procedure file and header file or are they same?
Edit 1 : The only difference I know is if I write DoWork() in procedure file, then I have to compile the procedure file and then pass the object code, while compiling the main program.
Thanks.
The preprocessor will – among other things – recursively replace all
#includedirectives by the code of these headers included. (Basically, it’s a dumb text replacement machine.) The result, a source file with all included headers recursively copied into it, is called a translation unit. Effectively, this is what your compiler sees (although modern compilers often mesh together different stages of the translation process in order to be faster).You can have multiple translation units contribute to a single resulting program. (In fact, with anything above 50 lines of code, that’s pretty much the standard.)
When you are defining functions in headers (as opposed to only declaring them), and the headers with these definitions are then included in multiple source files that are to be linked to some executable, then the linker will find multiple definitions of the same functions, and give up emitting a nasty error message.