Preprocessor directives will allow you to determine at compiling time which pieces of code will be processed from your source code (I suppose there must be other usages, so please reply if you know other).
One known example are the debug variables or messages. When you finish your job you can forget to delete all debugging messages. It won't be good if the customer clicks on a button and suddenly gets a "Oh Shit!!" as a message.
Well, you can avoid that with preprocessor directives. This is an example (I had to simulate the signal from an ADC). ADC was not available all the time, so I read from a plain text file the same way ADC data was gathered:
------------------------------------------------------------
#ifdef _USEFILESRC_
double SignalSource::read(){
//Read from a text file
}
#else
double SignalSource::read(){
//Read from ADC
}
#endif
-----------------------------------------------------------
That means: if _USERFILESRC_ has been defined when compiling then use the first function, otherwise, use the second function.
Next, the gcc command will look like this when compiling the application to read from the plain file:
gcc -Wall -D _USEFILESRC_ signalsource.cpp -o signalsource.o
And, when reading from ADC (Analog to digital conversor):
gcc -Wall signalsource.cpp -o signalsource.o
Another use for this technique is when writing code for different platforms, you can for example define register and interrupt variables and porting when compiling.
One known example are the debug variables or messages. When you finish your job you can forget to delete all debugging messages. It won't be good if the customer clicks on a button and suddenly gets a "Oh Shit!!" as a message.
Well, you can avoid that with preprocessor directives. This is an example (I had to simulate the signal from an ADC). ADC was not available all the time, so I read from a plain text file the same way ADC data was gathered:
------------------------------------------------------------
#ifdef _USEFILESRC_
double SignalSource::read(){
//Read from a text file
}
#else
double SignalSource::read(){
//Read from ADC
}
#endif
-----------------------------------------------------------
That means: if _USERFILESRC_ has been defined when compiling then use the first function, otherwise, use the second function.
Next, the gcc command will look like this when compiling the application to read from the plain file:
gcc -Wall -D _USEFILESRC_ signalsource.cpp -o signalsource.o
And, when reading from ADC (Analog to digital conversor):
gcc -Wall signalsource.cpp -o signalsource.o
Another use for this technique is when writing code for different platforms, you can for example define register and interrupt variables and porting when compiling.
Comments