We all know (or at least we should know) that we can use #define to create macros that replace names with values during the preprocessor phase of compilation. Sometimes, it’s very important for us to have the ability to change large amounts of code very quickly, because we have a new size limit for an object we rely on.
Configuration headers are headers you include in every source which only contains macros. This means that, if you need to change all of your network address targets from one ip to another, you simply have to modify the macro in the configuration file instead of tracking it through every file you have created.
The other benefit to configuration files is in activating and deactivating large segments of code quickly. Using the #if and #ifdef macros, we can mark off pieces of code to only run when/if we have certain items defined. That allows us to, for example, write a large amount of debugging code during our project and quickly deactivate it for release. When you have to do maintenance on the code again, you simply reactivate all of that debug code and it’s viable again.
A simple configuration header might look something like this:
#ifndef CONFIG_H #define CONFIG_H #define INET_TARGET_ADDR "127.0.0.1" #define INET_TARGET_PORT 1138 #define DEBUG 1 #define OPTIONAL_ONE 0 #endif
With a configuration header like this, there could be two options for DEBUG and OPTIONAL_ONE.
- If we used #if, DEBUG would work but OPTIONAL_ONE would not
- If we used #ifdef, DEBUG and OPTIONAL_ONE will both be active
- If we used #ifndef, DEBUG and OPTIONAL_ONE will both be inactive
For larger projects, consider one or two configuration headers. It can make a world of difference in how easy your code is to maintain.