Home > database >  Basic question about header file inclusion
Basic question about header file inclusion

Time:08-24

I'm creating a new project in keil to learn how to add files and headers and link them properly. I need some help in understanding the optimised way to add header files.

I've a main.h file, in that I've included FU68xx.h, adc.h and gpio.h file.

#ifndef HEADER_FILE  
#define HEADER_FILE

#include <FU68xx.h>  
#include "adc.h"  
#include "gpio.h"

#endif

In "adc.c" and "gpio.c" file i've included only main.h file and I'm able to compile successfully. But is this the right way to do it? is adding main.h file in all the files cause multiple inclusion of header files?

If I add the main.h file under #ifndef HEADER_FILE in the "adc.c" or "gpio.c" file, i get error while compiling about undefined identifiers.

CodePudding user response:

Multiple inclusion of the same header file is not a problem (and not a noticeable compile-time increase) if each header is appropriately protected with an "#ifndef" as you did.

Note that the name you used in that "#ifndef" must be unique (different in each header file), so the name "HEADER_FILE" is not very good - it would have been better to call it with a unique name, e.g., "INCLUDED_MAIN_H" (and other header files will use other names). Alternatively, all modern compilers support the "#pragma once" command which is better than ifndef in two ways:

  1. You don't need to invent a unique name (and risk that it's not unique)
  2. The compiler doesn't need to read the header file until the end just to look for the "#endif" - once it sees the "#pragma once" and knows this is the second time reading the same file, it immediately stops reading it.

But even though including the same header file is not a problem, including too many headers in a file that doesn't need it is a problem - it increases compilation time, and also increases incremental compilation time: If you change a header file, and a hundred other files include it, the build system (e.g., make) will need to re-compile all of these hundred other files. So usually I would recommend that each source file (.c) should include only the minimal set of header files that it really needs - rather than include some big "main.h" that includes everything.

  • Related