Approach for Static Allocation in "Shared Library" in Embedded Systems

We have a shared C library for several embedded systems that use static (i.e. compile time).

So, this means we usually have something that boils down to this (unless we want to change the shared source file):

#define TMR_MAX 100
int actual_number_of_timers;
SoftTimer softTimers[TMR_MAX];

      

In other words, to avoid malloc'ing, most of the space is actually wasted.

Or we can do this to have a new set of enums for each project:

enum TimerType
{
    TMR_KEYBOARD = 0,
    TMR_LCD,
    ...,
    TMR_MAX
};

SoftTimer softTimers[TMR_MAX];

      

This other case wastes no space, but it does mean that each project changes the file (say) timer.h

to define its own constants. Btw, timer example is just an example of a principle.

So, is there a smarter way to get something like a "fair size" compile time distribution that still allows us to have a common "frozen" codebase with separate tests?

+3


source to share


3 answers


Pass TMR_MAX

as a macro flag to your compiler. For example, for GCC, which will:

#include <stdio.h>

int main ()
{
    printf ("%d\n", TMR_MAX);
}

      



gcc main.c -DTMR_MAX=42 && ./a.out

gives 42

+1


source


How flexible is your toolchain, in particular the link editor? With the GNU toolchain and ELF chaining, you can have separate timer variables (instead of an array) and put them in a specific section:

SoftTimer softTimers __attribute__ ((section ("alloc_timers")));

      



GNU ld

will synthesize the special characters __start_alloc_timers

and __stop_alloc_timers

, which you could use to iterate over timers. You will of course have to identify the timers by their variable names (or pointers) and can no longer use enumeration constants for this.

+1


source


In the lines of Sergey's answer, move the definitions TMR_MAX

, etc. from the appropriate header files, but instead of defining them on the command line, you can have a file configuration.h

that is specific to each project:

// Configuration settings for project XYZ

#define TMR_MAX (3)
#define WIDGET_COUNT (23)
...

      

This will then be included in the source files, before all other headers:

// Widget-timing module for project XYZ

#include "configuration.h"
#include "timer.h"
#include "widget.h"
...

      

+1


source







All Articles