Jump to content
43oh

Compiler warnings when using pgm_read_word()


Recommended Posts

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.

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.

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...