【问题标题】:C preprocessor: concatenation of another defineC 预处理器:连接另一个定义
【发布时间】:2015-02-26 10:58:33
【问题描述】:

我正在使用 GCC 为 ARM 进行编码,需要将 (##) 名称与 a 定义连接起来,如下所示:

#define LCD_E_PORT GPIOC 
...
#define RCC_PORT(x) (RCC_APB2Periph_ ## (x)) // ???
...

这样在RCC_PORT(LCD_E_PORT) 之后我会得到RCC_APB2Periph_GPIOC。重要的是要说,LCD_E_PORTRCC_APB2Periph_GPIOC 不是字符串,而是一些低级系统定义的指针(访问它们的处理器内存映射)。

所有这一切的重点是拥有一个宏,它可以处理多个端口定义。

有解决办法吗?


我正在使用 arm-none-eabi-gcc。

【问题讨论】:

  • 如果你尝试#define RCC_PORT(x) RCC_APB2Periph_##x会发生什么?
  • 例如:RCC_PORT(LCD_E_PORT) 会导致RCC_APB2Periph_LCD_E_PORT 所以是错误的。我也尝试过双重定义,我的意思是:#define RCC_PORT1(x) RCC_PORT(x),但在RCC_PORT1(LCD_E_PORT) 之后出现RCC_APB2_Periph_ and "(" don't give a valid token 的错误,因为正如我所说,GPIOx 是(u32 *) ptr。就是这样或者不扩展宏,或者将宏扩展为最终定义……我需要的只是中间的定义。

标签: c c-preprocessor


【解决方案1】:

你需要的东西需要通过预处理器进行更多的间接处理:

这(定义.c):

#define TOKENPASTE( x, y ) x ## y
#define TOKENPASTE2( x, y ) TOKENPASTE( x, y )

#define LCD_E_PORT GPIOC
#define RCC_PORT(x)  TOKENPASTE2( RCC_APB2Periph_, x )

#define STRING(x) #x

int main( int argc, char* argv[] )
{
    RCC_PORT(LCD_E_PORT);
}

通过gcc -E defines.c我们得到预期的输出:

# 1 "defines.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "defines.c"
# 10 "defines.c"
int main( int argc, char* argv[] )
{
    RCC_APB2Periph_GPIOC;
}

更多信息请参见this SO question

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 2012-03-28
    • 1970-01-01
    • 2015-09-13
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    相关资源
    最近更新 更多