Destination: #define, #include, #undef

What would be the purpose of this construct in the c file:

#define _TIMERC #include "timer.h" #undef _TIMERC 

I am aware of protection to prevent multiple inclusion of the header file. It seems this is not what is happening.

thanks!

+3
source share
6 answers

Here is a script to illustrate ...

Suppose timer.h provides a tick_count () macro that returns the number of timer interrupts that have occurred.

One module (rpm_reader.h) using timer A for time synchronization:

 #define _TIMERA #include "timer.h" #undef _TIMERA 

Another module (lap_time.h) uses timer C for the time interval

 #define _TIMERC #include "timer.h" #undef _TIMERC 

rpm_reader will return the tick counter from timer A when it calls tick_count (), and lap_time will get its counter from timer C.

(My apologies for answering my own question, but asking the question helped me come to this revelation.)

+5
source

Often the library header file has several parameters that are activated and disabled using macros. This will allow such an option.

More typically, they are installed in the global scope, customizing your build system to add (for example, gcc) -D_TIMERC to the compilers command line.

+4
source

I was wondering if this could be:

The header file in this case is intended to provide several inclusions with different installed Defines before each #include.

If timer.h has a code block (interrupt code) for timers A, B and C for each timer in the microcontroller. In some cases, timer A is required in one module, and timer C is required in another module.

+2
source

I think your own answer is right. The included header most likely contains conditional material, and the “calling” file knows what specific set of conditional “things” it wants to include.

This is not necessarily related to several inclusions — these can only be special cases, depending on the context of the “call”.

I'm not quite sure why not decide. I can’t think of a case where I will mix and match, so I don’t know why uncertainty is needed.

+1
source

At the risk of specifying the obvious, "timer.h" expects _TIMERC and the rest of your code to be gone.

Obviously, this is not good practice in the general case, but I saw this when including third-party code. It can be frustrating when you have #defs that collide ...

0
source

For recording, the usual practice of avoiding multiple inclusion of the same header file is to place the guard in the file itself, rather than relying on some external definition ... ^ _ ^

Headings begin with:

 #ifndef header_name_h #define header_name_h 

and end with:

 #endif 

Of course, the def style can change.

Thus, the first time we turn on, we pass by #ifndef (not yet defined), and we set the macro. The second time you turn it on, if there is one, we simply go to the end of the file, nothing is turned on.

0
source

All Articles