Enums in Bitfields [Greenhills PowerPC Compiler for C]

8 visualizzazioni (ultimi 30 giorni)
I have an enum
typedef enum
{
YES = 0u,
NO = 1u
} AnswerType;
Which is used as a bit field element in a struct
typedef struct
{
uint8_t messageField;
uint8_t padding : 7;
AnswerType answer : 1;
} MessageType;
When attempting to access this field, Polyspace is confusing the enum to be a signed 1 bit bitfield with a range of [-1..0], when in fact it's unsigned [0..1]. This of course causes a chain of errors due to incorrect range values.
Forcing the "auto-unsigned-first" option in Polyspace for "-enum-type-definition" will treat this enum as a u8, however it's actually compiled as u32, thus causing problems in other areas of the analysis (where we rely on it being a u32).
Is there a way to override the range values for enums and struct elements?

Risposta accettata

Alexandre De Barros
Alexandre De Barros il 29 Gen 2017
Hello,
Polyspace is not confused but the actual type of an enum (and its signedness) is implementation-dependent.
See this link for a reference to the C standard on this topic.
Some C coding standards like MISRA-C:2012 highlight this problem, with the rule 6.1 "Bit-fields shall only be declared with an appropriate type".
Now, you can have unsigned bitfields by choosing a gnu compiler in your Polyspace project.
But a more portable solution is not to rely on the representation of enums with bitfields.
For example, you could use constants instead:
typedef unsigned int AnswerType;
const AnswerType YES = 0u;
const AnswerType NO = 1u;
Regards,
Alexandre
  1 Commento
Mark R
Mark R il 30 Gen 2017
Firstly thanks for the response.
I have never used typedef constants like that before, nice solution. I will consider this in future.
Unfortunately portability was not a goal of my project and so I developed the software relying on the behaviour of the compiler.
I'm toward the end of my project and as such I can't justify a large change to simply work around an analysis tool.
Luckily - I used the gnu dialect option as you suggested and that has fixed the errors I'm seeing. Thanks again for your help.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by