Using multiple files
Location
-
Courses
/
-
Quick C course
/
Using multiple files
Until now, we only used one file. It is time to learn to divide our code into multiple files.
Avoiding multiple definitions
Let us say we use 4 files: A, B, C and D. The file A defines a function called 'func'. The file B and the file C both include the file A. If the file D includes the file B and C, there will be an error, because 'func' will be defined two times (One time from the file B and an other from C).
We avoid that kind of problem by using two kinds of file. Source files (.c) and header files (.h).
The source files contain the definition of the functions and the header files simply declare them.
We only include header files, that way, a function will never be defined more than one time.
Include guards
To avoid header files being included many times inside the same file, we use what is called 'include guards'.
To do so, we use what is called 'preprocessor directives'. We will put the code of our header files between:
#ifndef NAME_OF_THE_FILE_H
#define NAME_OF_THE_FILE_H
And that:
#endif
Basically, those directives will let the code inside be included only if the macro 'NAME_OF_THE_FILE_H' is not defined. If it is not defined, it defines it, so the next time it is not included again.
A complete example
We create a header file declaring the function 'printInt':
printInt.h
1
2
3
4
5
6
#ifndef PRINT_INT_H
#define PRINT_INT_H
void printInt(int num);
#endif
We define the function inside a source file:
printInt.c
1
2
3
4
5
6
#include <stdio.h>
void printInt(int num)
{
printf("%d\n", num);
}
We only include the header file 'printInt.h':
main.c
1
2
3
4
5
6
7
8
#include "printInt.h"
int main()
{
printInt(12345);
return 0;
}

Note that when we include files from our project, we use quotes instead of <>.