2

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.

Piero
  • 79
  • 5
  • 1
    Not necessary in your specific case, but usually is done because headers might contain some declarations needed for the implementation. Don't forget include guards BTW – Eugene Sh. May 18 '21 at 20:11
  • 2
    https://softwareengineering.stackexchange.com/questions/286490/what-is-the-difference-between-function-and-functionvoid/287002 Summary: use `int testFunction(void)` instead of `int testFunctio()` – William Pursell May 18 '21 at 20:37

2 Answers2

2

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.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

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...