All across our C code base, I see every macro defined the following way:
#ifndef BEEPTRIM_PITCH_RATE_DEGPS #define BEEPTRIM_PITCH_RATE_DEGPS 0.2f #endif #ifndef BEEPTRIM_ROLL_RATE_DEGPS #define BEEPTRIM_ROLL_RATE_DEGPS 0.2f #endif #ifndef FORCETRIMRELEASE_HOLD_TIME_MS #define FORCETRIMRELEASE_HOLD_TIME_MS 1000.0f #endif #ifndef TRIMSYSTEM_SHEARPIN_BREAKINGFORCE_LBS #define TRIMSYSTEM_SHEARPIN_BREAKINGFORCE_LBS 50.0f #endif
What is the rationale of doing these define checks instead of just defining the macros?
#define BEEPTRIM_PITCH_RATE_DEGPS 0.2f #define BEEPTRIM_ROLL_RATE_DEGPS 0.2f #define FORCETRIMRELEASE_HOLD_TIME_MS 1000.0f #define TRIMSYSTEM_SHEARPIN_BREAKINGFORCE_LBS 50.0f
I can't find this practice explained anywhere on the web.
A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive. Here's an example. #define c 299792458 // speed of light. Here, when we use c in our program, it is replaced with 299792458 .
"Using macros can reduce the readability of your code. When you use them, you're basically creating a set of nonstandard language features."
You can use it inside a function, but it is not scoped to the function. So, in your example, the second definitions of a macro will be a redefinition and generate an error.
In computer programming, macros are a tool that allows a developer to re-use code. For instance, in the C programming language, this is an example of a simple macro definition which incorporates arguments: #define square(x) ((x) * (x))
This allows you to override the macros when you're compiling:
gcc -DMACRONAME=value
The definitions in the header file are used as defaults.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With