10 years, 7 months ago.

Creating a static lookup table

I have some named numbers that never change during the life time of my program which I need to be able to lookup by name. Since these name value pairs never change I want to define then either using the define compiler directive or as const so they get stored in flash and not use up the RAM.

So far the best I have come up with is to define all the constants then create a map in memory and fill it with the constants, e.g.

#include <string>
#include <map>

#define X0 "X0"
#define X0I 200

class SomeClass {

         map<string, int> m;

         SomeClass() {
               m[X0] = X0I;
         }
}

I know c++ 11 allows you to fill a map at the point its created, some thing like:

const map<string,int> myMap = {
   {"X0", 2},
   {"X1", 4},
   {"X2", 6}
};

But doesn't look like mbed supports this at the moment.

Does anyone know of a good way of doing this on an mbed?

2 Answers

10 years, 7 months ago.

Hi,

Here is a simple solution :

const int table[] = { 2, 4, 6};

int lookup(const char *s)
{
    return table[atoi(&s[1])];
}

int main()
{
    printf("%d\n", lookup("X0"));
    return 0;
}

Thanks for the response. I've not used the 'atol' function before, I'm new to c++, but presumably the result of calling atol has to map to the correct point in the array meaning that the string must have some intrinsic link to the point in the array. I want to use any arbitrary string as the key, would this solution support that?

posted by Ollie Milton 19 Sep 2013
10 years, 7 months ago.

Or:

const struct map {
   char *str;
   int num;
} myMap[] = {
   {"X0", 2},
   {"X1", 4},
   {"X2", 6}
};

But I'm not so sure that 'const' variables are actually stored in flash. E.g. in WINAVR you need quite some attributes and functions to achieve that.

Thanks this looks good. according to the memory model description in the mbed hand book anything defined as constant is stored in flash. I'll give it a go, cheers.

posted by Ollie Milton 19 Sep 2013