Search code examples
carrayspic18

Declaring large arrays on PIC18


I'm trying to declare a 512 byte array in MPLAB X v2.26, using compiler XC8 v1.32. My target is a PIC18F66K90 (4k of RAM).

If I declare the array inside any function, main for example, I get an error.

#define buffSize 512

int main (void) {
    char buffer[buffSize];
    ...
}

error: (1250) could not find space (512 bytes) for variable _buffer

If I declare the array globally, I don't get an error.

#define buffSize 512
char buffer[buffSize];

int main (void) {
    ...
}

All good and happy

I've looked at the manual for the processor and the compiler's user guide and suspect the problem has to do with RAM banks (16 banks of 256 bytes each). My program is working with the array declared globally, but I'm curious about why it must be done this way. Is it best practice? Do you have any tips or ideas?

Thank you, James


Solution

  • From the xc8 user guide 3.5.2.2 and 3.5.2.3

    Auto variables, the default type for local variables, are stored on the compiled stack. They come into existence when a function is executed and disappear once the function returns. Each item on the compiled stack must fit within one bank of data memory (256k for PIC18F66K90). Use the static keyword to change the type to non-auto, so that it is stored in general memory and thus, can be larger than one bank of memory.

    #define buffSize 512
    
    int main (void) {
        static char buffer[buffSize];
        ...
    }
    

    This is what I'm using now and it works. Thank you for the pokes in the right direction.