johnsondavies

Compiler warnings when using pgm_read_word()

4 posts in this topic

I am storing data in program memory using PROGMEM, and reading it using pgm_read_byte() and pgm_read_word(), to save RAM.

However, the compiler gives warnings:

In function 'int lookupnumber(int)':
warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

I've read that it's not good practice to ignore these warnings, but I can't see how to eliminate them. A demonstration program is:

const int numbers[] PROGMEM = { 2, 3, 5, 7, 11, 13, 17, 23 };

int lookupnumber (int i) {
  return pgm_read_word(&numbers[i]);
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println(lookupnumber(4));
  for (;;);
}

Thank you.

Share this post


Link to post
Share on other sites

Unless you care about portability to Atmel Arduinos, there's no need to use progmem with Energia. The compiler will put anything that's declared as const into flash memory.

energia likes this

Share this post


Link to post
Share on other sites

For a bit of background:

Atmel AVR (the chip in the original Arduino) has a Harvard Architecture, which separates program memory (i.e. Flash) from data (i.e. RAM). It uses special assembly commands to read program memory. That's why you need to tell the compiler if you want to store a variable in Flash or access data that's stored in Flash.

Most other MCUs have a Von Neumann architecture with a unified address space for all types of memory. All access to memory can use the same commands and the compiler decides on where to put things, depending on whether a variable is read-only (Flash) or read-write (RAM).

To maintain compatibility with code written for AVR, Energia and other non-AVR Arduino implementations replace progmem related commands to basically do nothing without having the compiler complain too much. For the MSP430 see:
https://github.com/energia/Energia/blob/master/hardware/msp430/cores/msp430/avr/pgmspace.h

The warning you see is because the replacement for pgm_read_word casts your int to a short.

 #define pgm_read_word(addr) (*(const unsigned short *)(addr))

If you want to get rid of the warning while keeping pgm_read, you could declare your array as an unsigned short instead of int.

 

tripwire and energia like this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now