Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only define a macro if it's not already defined?

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.

like image 356
Trevor Hickey Avatar asked Sep 04 '15 12:09

Trevor Hickey


People also ask

What is correct way to define macro?

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 .

Why macros should not be used?

"Using macros can reduce the readability of your code. When you use them, you're basically creating a set of nonstandard language features."

Can we define macro inside main function?

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.

How do you define macro explain it with example?

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))


1 Answers

This allows you to override the macros when you're compiling:

gcc -DMACRONAME=value 

The definitions in the header file are used as defaults.

like image 186
Barmar Avatar answered Sep 28 '22 03:09

Barmar