Searock
Searock

Reputation: 6498

Method in header files

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.

Upvotes: 3

Views: 2340

Answers (2)

pmg
pmg

Reputation: 108988

It all boils down to "project management".

In every project all functions must be named uniquely (exceptions notwithstanding) so that the linker can complete the program by generating calls to the right functions.

In a small project (like your "work" project above) it's easy to see there's no duplication of code, but as time goes by and your project grows things get harder to manage. If several of your '.c' files #include "work.h", each of them will get a copy of the function definition DoWork. If you put the function definition in a '.c' file ot it's own and a declaration in a '.h' file, there will be no misshaps.

function declaration: tell the compiler how to use the function
function definiton: tell the compiler what the function does

Upvotes: 1

sbi
sbi

Reputation: 224149

The preprocessor will - among other things - recursively replace all #include directives 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.

Upvotes: 3

Related Questions