In what situations we need to use .h
file and when to use the .c
file in C.
Are they two alternatives for a same purpose?.
Please explain.
Asked
Active
Viewed 883 times
1

reddi hari
- 173
- 1
- 12
-
7never `#include file.c`. – Fantastic Mr Fox Sep 30 '21 at 05:19
-
4When to use ```#include "file.c"```? Basically never. There's a few rare edge cases, but as the saying goes, "if you have to ask..." – sj95126 Sep 30 '21 at 05:19
-
Related: https://stackoverflow.com/q/50593094/2472827. – Neil Sep 30 '21 at 05:24
-
2Where ever you found `#include "file.c"`, it is plain wrong with near 100% probability. You will know if you need to do it, and you will have enough experience. Until then, see it as an error. -- However, if you have a specific example that led to this question, please add it to your question. – the busybee Sep 30 '21 at 06:14
1 Answers
3
- Never include .c files
- If you include something, it should be a .h file.
- Code goes into code files, .c.
- Headers, .h files, contain only what can be compiled more than once, i.e. declarations, macro definitions, more includes.
- If necessary, headers use reinclusion guards.
Whenever you feel tempted to include a .c file, you instead want to add it to your project so that it gets processed during building, i.e. gets compiled by its own and in a further build step gets linked into the created binary.

Yunnosch
- 26,130
- 9
- 42
- 54
-
1More on what goes where and why https://stackoverflow.com/a/46440374/7733418 (one of my other answers). – Yunnosch Sep 30 '21 at 06:31