Final step - header file protection
The last thing to do before our conversion is complete, is to protect our header files from multiple inclusion. Take the following example. Say that Main and ADC both refer to each other:
Main.h
ADC.h
What happens when this is compiled? The preprocessor will look at Main.h, then include ADC.h. However, ADC.h includes Main.h, which again includes ADC.h, etc...
To guard against this problem, we can use preprocessor defines. The following code snippet is the basic protection setup:
Code:
#ifndef MAIN_H
#define MAIN_H
// Header file contents
#endif
This construct, when applied to each of your header files, will protect against multiple inclusions. As each C file is compiled, the associated header file is included, as well as any other referenced header files (via includes in the C file's header file). As each header is included, a check is performed to see if the header's unique token is already defined, and if so the inclusion halts to prevent recursion. If the token is not already defined, the preprocessor defines it and looks at the remainder of the header file's contents. By giving each header file a different token (typically the header's filename in ALL CAPS, and the period replaced by an underscore), this system will prevent any preprocessor troubles.