including a header file in the .c file that contains its definitions

Viewed 54

I have the following files:

main.c

#include <stdio.h>
#include "test.h"

int main(){
    printf("%d", testFunction());
    return 0;
}

test.h

int testFunction();

test.c

int testFunction(){
    return 1;
}

should i include test.h in test.c?

test.c

#include "test.h" //is this necessary?

int testFunction(){
    return 1;
}

If I run the main, there are no errors in either case.

2 Answers

Q: should i include test.h in test.c?

A: Generally, yes.

It's essential with a more complex header that contains constants, struct definitions, etc. It's "good practice" in any case.

ALSO: Don't forget to add header guards to your .h file.

EXAMPLE:

#ifndef TEST_H
#define TEST_H

int testFunction();

#endif

If you prefer, most compilers also support #pragma once as an alternative.

It is not necessary in your case, but may save you from trouble as your program gets more complicated. A function declaration e.g.

int f1(int x);

should be seen by the compiler before the function call e.g.

return f1(5);

so that it knows what to expect. Using a header file myheader.h

int f1(int x);

and main.c

#include "myheader.h"

int main(){
    return f1(5);
}

int f1(int x){
    return x*x;
}

ensures this is happening, try removing the header file in this example and you get into trouble...

Related