我正在尝试在微控制器库中编写一个宏 set_DIR() 。
我的计划:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
typedef struct VPORT_struct
{
uint8_t DIR;
uint8_t OUT;
uint8_t IN;
uint8_t INTFLAGS;
} VPORT_t;
#define VPORTA (*(VPORT_t *) 0x0000)
#define VPORTB (*(VPORT_t *) 0x0004)
#define VPORTC (*(VPORT_t *) 0x0008)
// ... etc.
#define set_DIR(x, y) x ## .DIR |= ## y
#define PORT VPORTA /* may be chanched e.g. VPORTC */
int main(void)
{
set_DIR(PORT, 3);
return 0;
}
我想要这样的约定:
set_DIR(PORT, 3);
我期望:
VPORTA.DIR |= 3
有两个问题。
首先:上面的代码生成的错误没有将 PORT 转换为 VPORTA。
main.c: In function ‘main’:
main.c:24:11: error: pasting "PORT" and "." does not give a valid preprocessing token
24 | set_DIR(PORT, 3);
| ^~~~
main.c:18:23: note: in definition of macro ‘set_DIR’
18 | #define set_DIR(x, y) x ## .DIR |= ## y
| ^
main.c:18:33: error: pasting "|=" and "3" does not give a valid preprocessing token
18 | #define set_DIR(x, y) x ## .DIR |= ## y
| ^~
main.c:24:3: note: in expansion of macro ‘set_DIR’
24 | set_DIR(PORT, 3);
| ^~~~~~~
第二:用点连接生成错误。
我该如何修复它?
将
#define set_DIR(x, y) x ## .DIR |= ## y
更改为:
#define set_DIR2(x, y) (x).DIR |= (y)
#define set_DIR(x, y) set_DIR2(x, y)