0

Let's say I have following definitions in C++

  struct ControlReg
  {
    uint32_t reset_bit : 1;
  };

  struct ConfigReg
  {
    uint32_t even_channel_value : 16;
    uint32_t odd_channel_value : 16;
  };

  struct PeripheralRegs
  {
    volatile ControlReg control_reg;
    volatile uint32_t status_reg_01[2];
    volatile uint32_t status_reg_02[2];
    volatile ConfigReg config_reg_01[8];
    volatile ConfigReg config_reg_02[8];
    volatile uint32_t status_reg_03[2];
  };

Can anybody tell me what consequences will have usage of below given definitions of the bit fields instead?

  struct ControlReg
  {
    volatile uint32_t reset_bit : 1;
  };

  struct ConfigReg
  {
    volatile uint32_t even_channel_value : 16;
    volatile uint32_t odd_channel_value : 16;
  };

As far as my compiler I have been using the ARM v7 g++.

  • bit fields are implementation specific, so providing compiler information might help. – Jarod42 May 28 '21 at 08:19
  • Do you really need `volatile` (especially as it is misused most of the time)? – Jarod42 May 28 '21 at 08:20
  • Making part of a struct volatile is a bad idea. Typically you either want the whole struct to be volatile or you don't. What problem are you trying to solve with this? – Lundin May 28 '21 at 10:43
  • According to my (bad) experience, you cannot rely on volatile (or const) keywords within typedefinitions, especially not inside compounds. I only trust those keywords to be explicitly used in definition and declaration of whole variables. – Yunnosch May 28 '21 at 10:52
  • @Lundin I have encountered that without the 'volatile' keyword and optimization level set to O2 level writing into the status and config registers doesn't work. So I have been looking what could be the reason for that. – Professor Jimatura May 28 '21 at 12:45
  • Naturally all registers must be volatile or the compiler might optimize away access to them. – Lundin May 28 '21 at 12:57
  • @Lundin I don't understand why with code optimization at level O0 the writing into the registers worked without volatile keyword in the bitfields. – Professor Jimatura May 28 '21 at 13:19
  • @ProfessorJimatura Because then the optimizer was disabled. Here's how a compiler works: if you write to some variable but never use that variable after that, the compiler will remove the write since it considers it unnecessary. Now if the variable happens to be a hardware register, then that optimization will break everything since nothing will get written. By volatile-qualifying all such registers, we prevent incorrect optimizations from taking place. – Lundin May 28 '21 at 13:25

0 Answers0