C header file

How to use C header files to divide a program into multiple files

You can put a simple program in a file, but when the program becomes larger, it is impossible to save everything in one file.

You can move parts of the program into separate files and create ahead File.

The header file looks like a normal C file, but it ends with.hinstead.c, Instead of the implementation of your functions and other parts of the program, it containsCustoms declaration.

first time usingprintf()Function or other I/O function, you must enter:

#include <stdio.h>

use it.

#includeIs anPreprocessorInstructions.

Preprocessor to findstdio.hThe file is in the standard library because you used square brackets. To include your own header file, you will use quotation marks as follows:

#include "myfile.h"

The above will checkmyfile.hIn the current folder.

You can also use the folder structure for libraries:

#include "myfolder/myfile.h"

Let us take an example. The program calculates the years since a given year:

#include <stdio.h>

int calculateAge(int year) {
  const int CURRENT_YEAR = 2020;
  return CURRENT_YEAR - year;
}

int main(void) { printf("%u", calculateAge(1983)); }

Suppose i want to movecalculateAgeFunction into a separate file.

I create acalculate_age.cfile:

int calculateAge(int year) {
  const int CURRENT_YEAR = 2020;
  return CURRENT_YEAR - year;
}

one leftcalculate_age.hI put the fileFunctional prototype, This function is the same as.cDocuments, except the text:

int calculateAge(int year);

Now in the main.cWe can remove the filecalculateAge()Function definition, we can importcalculate_age.h, Which will makecalculateAge()Available functions:

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

int main(void) {
  printf("%u", calculateAge(1983));
}

Don't forget to compile a program composed of multiple files, you need to list them all on the command line, as shown below:

gcc -o main main.c calculate_age.c

For more complex settings, there must be a Makefile to tell the compiler how to compile the program.

Download mine for freeC manual


More clang tutorials: