是否可以在同一标头中向前声明一个静态const int?

问题描述 投票:0回答:1

与标题相同:我想向前声明一个整数,以便可以在定义整数之前使用它,但所不同的是,它需要在完全相同的头文件中发生。

我的代码如下:

//Embedded system header file for pins and UART.

#if peripheral
#define P4_2 18
#define P4_3 17

static const int AUX_UARTRXD = P4_2;    /* Receive  Data (RXD) at P4.2 */
static const int AUX_UARTTXD = P4_3;    /* Transmit Data (TXD) at P4.3 */

#undef P4_2
#undef P4_3
#endif

static const int P4_2 18
static const int P4_3 17 

我真的很想用一种象征性的方式来初始化AUX_UARTRXD,但是我的解决方案确实很丑陋。

移动声明是一个选项,但这意味着将更改头文件的默认模式。

c forward-declaration
1个回答
0
投票

我在您的解决方案中不喜欢的是,您必须将值1718定义两次。如果您必须修改它,并引入misalignance risk。]],将是一件很痛苦的事情。

这不是您要的正向声明,但是如果您为值再添加两个定义,该怎么办?

// Outside #if peripheral
#define P4_2_VAL 18
#define P4_3_VAL 17

#if peripheral
static const int AUX_UARTRXD = P4_2_VAL;    /* Receive  Data (RXD) at P4.2 */
static const int AUX_UARTTXD = P4_3_VAL;    /* Transmit Data (TXD) at P4.3 */
#endif

static const int P4_2 P4_2_VAL
static const int P4_3 P4_3_VAL

通过这种方式,您还可以摆脱那些#undef

© www.soinside.com 2019 - 2024. All rights reserved.