指向处理器固定地址的constexpr指针

时间:2018-10-07 18:13:01

标签: c++11 embedded constexpr

我已经阅读了有关该主题的所有帖子。可以理解,不能在constexpr中使用静态变量,因为直到链接时才知道它们。但是我不明白为什么编译器将不允许创建指向真正静态地址的静态指针。

由于“嵌入式编程的许多优点”,我们一直在将代码转换为C ++ 11。这个特殊的问题令人不安。这是使它起作用的各种尝试。

#define PERIPH_BASE   0x40000000U
#define GPIOH_BASE    (AHB1PERIPH_BASE + 0x1C00U)
#define GPIOH         ((GPIO_TypeDef *) GPIOH_BASE)

#define KBATH_NFAULT_GPIO_Port GPIOH

// Attempt #1
const  GPIO_TypeDef* KBATH_NFAULT_GPIO_Port = (GPIO_TypeDef*)GPIOH_BASE;
constexpr DigitalInput BathNFaultK {const_cast<GPIO_TypeDef*> 
    (KBATH_NFAULT_GPIO_Port), BATH_NFAULT_Pin};

// Attempt #2
constexpr GPIO_TypeDef*  KBATH_NFAULT_GPIO_Port = (GPIO_TypeDef*)GPIOH_BASE;
constexpr DigitalInput BathNFaultK {KBATH_NFAULT_GPIO_Port, BATH_NFAULT_Pin};

// Attempt #3
#define STM_PERIPH(a) __builtin_constant_p (a) ? a : a
constexpr DigitalInput BathNFaultK {
    STM_PERIPH((GPIO_TypeDef*)GPIOH_BASE), BATH_NFAULT_Pin};

// Attempt #4
static constexpr inline GPIO_TypeDef* STM_GPIO_PORT(GPIO_TypeDef* p){
    return __builtin_constant_p((p))?(p):(p);
}
constexpr DigitalInput BathNFaultK {
    const_cast<GPIO_TypeDef*>(STM_GPIO_PORT(BATH_NFAULT_GPIO_Port)), 
    BATH_NFAULT_Pin
};

在常规“ C”中,这是可以接受的。有解决方案吗?这是在C ++ 17中解决的吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我将撤回此问题。目的是找到一种定义简单对象的方法,该对象可以在编译时使用,而无需实际实例化该对象。 constexpr是唯一想到的解决方案。也许这个问题是无效的。