Macro as a parameter to another macro

﹥>﹥吖頭↗ 提交于 2020-11-28 08:29:04

问题


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?


回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/23021074/macro-as-a-parameter-to-another-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!