Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro as a parameter to another macro

I'm trying to pass the parameters to macro SETBIT with another predefined macro like this:

#define SETBIT(ADDRESS,BIT,N) {(N) ? (ADDRESS &= ~(1<<BIT)) : (ADDRESS |= (1<<BIT))}
#define DAC_SYNC PORTB,3,POS
SETBIT(DAC_SYNC);

However I receiver error:

macro SETBIT requires 3 parameters only 1 given

There is an article with the following recommendations:

to prevent misnesting of arithmetic operations: #define foo (a,b) or #define bar(x) lose((x))

But even though I still have an error. BTW, reading the article I've indicated I can make the following conclusion: preprocessor expands ALL macroses appearing. But actually it looks like macro #define DAC_SYNC PORTB,3,POS is not expanding by preprocessor.

Could anyone make more clear how the GCC's preprocessor works?

like image 487
Roman Matveev Avatar asked Apr 11 '14 19:04

Roman Matveev


People also ask

Can a macro trigger another macro?

Here is an example of how to run another macro from a macro using the Call Statement. Just type the word Call then space, then type the name of the macro to be called (run). The example below shows how to call Macro2 from Macro1.

How do you pass a macro as a parameter?

To assign a macro that you pass arguments to a button, shape, image, or any object, you first right-click that object and click Assign Macro and then type the name of the macro and the argument, following the pattern described in the above examples, and then click OK. 'show_msg "I clicked a button!"'

Can a macro call another macro in C?

Short answer yes. You can nest defines and macros like that - as many levels as you want as long as it isn't recursive.

Can you combine two macros in Excel?

Multiple macros can be combined into a single macro, so the user only has to run this master macro instead of all the individual macros.


2 Answers

This works:

#define SETBIT2(ADDRESS,BIT,N) ((N) ? (ADDRESS &= ~(1<<BIT)) : (ADDRESS |= (1<<BIT)))
#define SETBIT(PARAMS) SETBIT2(PARAMS)
#define PORTB 5
#define POS 7
#define DAC_SYNC PORTB,3,POS

int main() {
  int a = SETBIT(DAC_SYNC);
  return 0;
}
like image 162
ooga Avatar answered Sep 24 '22 19:09

ooga


Just for the sake of completeness, that same manual you are linking to also states:

The number of arguments you give must match the number of parameters in the macro definition. When the macro is expanded, each use of a parameter in its body is replaced by the tokens of the corresponding argument.

So ooga's example is a nice demonstration of how macro expansion works recursively, first the outer macro gets expanded, then the argument.

like image 39
Mali Remorker Avatar answered Sep 23 '22 19:09

Mali Remorker