Wednesday, January 5, 2022

[SOLVED] Define array in header and storing it in stack

Issue

I need to define a global array which has to be visible in every file. I declared it in a header file, but it's stored in heap e not in stack. How can i put it in stack? Thank you

EDIT: I'm using an ATMEGA32 and array is put at the begin of the RAM (address 0x0060), while I need to put it at the end (address 0x085F)

common.h

#define dimension 5
unsigned int board[dimension][dimension];

main.c

#include "common.h"

Solution

You have a definition of the array variable in the header file. If you include it in more than one file you will have duplicate (or multiple) definitions of the same global variable which will be reported as an error by the linker.

In the header file you should have a declaration only like

extern unsigned int board[dimension][dimension];

and a definition in exactly one C file at file scope, i.e. not in a function. For example you can use this definition in main.c

unsigned int board[dimension][dimension];

It must be this way if you want to access the variable from more than one .c file.


To put this variable on the stack it must be inside a function, e.g. in main(), but this way you cannot use it as a global variable. You could use a pointer variable as a global variable and initialize this in main() with the address of the array. This has the drawback that the functions that use the pointer cannot determine the two array dimensions from the variable itself. Of course they could use the preprocessor symbol.

Example:

common.h

#ifndef COMMON_H
#define COMMON_H

#define dimension 5
extern unsigned int (*board)[dimension];

#endif // COMMON_H

main.c

#include "common.h"
#include "other.h"

unsigned int (*board)[dimension];

int main(void)
{
    unsigned int the_board[dimension][dimension] = {{ 0 }};

    board = the_board;

    printf("board[1][2] = %d\n", board[1][2]);

    some_function();

    printf("board[1][2] = %d\n", board[1][2]);

    return 0;
}

other.h

#ifndef OTHER_H
#define OTHER_H

void some_function(void);

#endif // OTHER_H

other.c

#include "common.h"
#include "other.h"

void some_function(void)
{
   board[1][2] = 3;
}

If you want to have the variable at a specific address or in a specific address range (but not on the stack) you could use a (linker specific) linker script to define a memory section at a specific address range and use a (compiler specific) #pragma section("name") or __attribute__((section("name"))) to put a normal global variable into this memory section.



Answered By - Bodo