Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between including a .c file and a .h file

Lot of the times when I watch other people's code I see some are including a .h file and some are including a .c/.cpp file. What is the difference?

like image 752
odbhut.shei.chhele Avatar asked Aug 25 '14 09:08

odbhut.shei.chhele


2 Answers

It depends on what is in the file(s).

The #include preprocessor directive simply inserts the referenced file at that point in the original file.

So what the actual compiler stage (which runs after the preprocessor) sees is the result of all that inserting.

Header files are generally designed and intended to be used via #include. Source files are not, but it sometimes makes sense. For instance when you have a C file containing just a definition and an initializer:

const uint8_t image[] = { 128, 128, 0, 0, 0, 0, ... lots more ... };

Then it makes sense to make this available to some piece of code by using #include. It's a C file since it actually defines (not just declares) a variable. Perhaps it's kept in its own file since the image is converted into C source from some other (image) format used for editing.

like image 130
unwind Avatar answered Sep 20 '22 02:09

unwind


.h files are called header files, they should not contain any code (unless it happens to contain information about a C++ templated object). They typically contain function prototypes, typedefs, #define statements that are used by the source files that include them. .c files are the source files. They typically contain the source code implementation of the functions that were prototyped in the appropriate header file.

Source- http://cboard.cprogramming.com/c-programming/60805-difference-between-h-c-files.html

like image 39
MSHasan Avatar answered Sep 21 '22 02:09

MSHasan