constexpr函数返回全局变量ref或全局变量

时间:2020-04-08 09:24:52

标签: c++ c++11 avr-gcc platformio

我正在arduino nano(旧的引导程序)上编写c ++程序。我尝试应用this方法来定义寄存器和其他硬件的全局变量。但是,当尝试在constexpr函数中使用此全局变量时,遇到了一个奇怪的问题。尽管我的代码已在Arduino IDE中正确编译,并且我也验证了结果(内存地址正确等),但platformIO还是不错的。可以使用以下代码说明该问题:

// globals.h
typedef volatile uint8_t register_t;
extern register_t g_PORTA;
// globals.S
.global g_PORTA
g_PORTA = 0x12
// main.h
class RegWrapper
{
  register_t& reg;
public:
  constexpr RegWrapper(register_t& r) : reg(r) {}
};

struct StaticFieldRef
{
  static constexpr register_t& Port = g_PORTB;  // Works properly
  static constexpr RegWrapper r = RegWrapper(Port);
};

struct ConstexprFunction
{
  static constexpr register_t& Port() // Arduino IDE doesn't complain, but PIO does
  {
    return g_PORTB;
  }
  static constexpr RegWrapper r = RegWrapper(Port());
};
//main.cpp just use the code somehow so it compiles

当试图返回对该全局变量的引用或指针时,更不用说将更复杂的表达式应用于return语句了,我得到一个错误:

note: 'static constexpr register_t& ConstexprFunction::Port() [with register_t = volatile unsigned char]' is not usable as a constexpr function because:
     static constexpr register_t& Port()
                                  ^
 error: expression 'g_PORTB' has side-effects

我了解编译器认为我正在尝试在constexpr上下文中更改全局变量的值,但是正如我所说的,在pio,arduino ide和clang分析器之间,行为并不相同。

我正在使用sublime文本的deviot插件。

PlatformIO, version 4.3.2a1
(platform: atmelavr; board: nanoatmega328; framework: arduino; build_type: debug)

0 个答案:

没有答案