如何定义跨行的宏

宏定义只能在一行

  • 如果宏定义有多行的话,编译器会报错。如下:
// 宏定义,定义了多行
#define insert_item(item,ps) do{
	item->prev = NULL;
	item->next = ps;
	if(ps != NULL) ps->prev = item;
	ps = item;
} while(0)
// 会报如下错 
content.c:17:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
  item->prev = NULL;
      ^~
content.c:18:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
  item->next = ps;
      ^~
content.c:19:2: error: expected identifier or ‘(’ before ‘if’
  if(ps != NULL) ps->prev = item;
  ^~
content.c:20:2: warning: data deFinition has no type or storage class
  ps = item;
  ^~
content.c:20:2: warning: type defaults to ‘int’ in declaration of ‘ps’ [-Wimplicit-int]
content.c:20:7: error: ‘item’ undeclared here (not in a function); did you mean ‘system’?
  ps = item;
       ^~~~
       system
content.c:21:1: error: expected identifier or ‘(’ before ‘}’ token
 } while(0)
 ^
content.c:21:3: error: expected identifier or ‘(’ before ‘while’
 } while(0)
   ^~~~~

如何解决

  • 加个反斜杠就好了。因为加了反斜杠后,编译器会自动忽略行尾的换行符。编译器会认为这几行的代码都是在一行里。
// 加上反斜杠
#define insert_item(item,ps) do{\
	item->prev = NULL;\
	item->next = ps;\
	if(ps != NULL) ps->prev = item;\
	ps = item;\
} while(0)

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...
win11本地账户怎么改名?win11很多操作都变了样,用户如果想要...