Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a best way of defining a very large array (lookup table)?

Tags:

c++

arrays

I have to define a large array (lookup table) in a code. It contains 256 elements and takes nearly 1 computer screen.

There are two functions that are using this array. I want to define this array under functions, so I could access them very quickly during development.

But if I try to do it inside one file, compiler will give "Undeclared identifier" errors around functions - because they use array.

So, I must put the functions and the array to separate files.

Here is the structure of my program:

main.cpp:

#include "lookup.h"

...uses two functions...

-

lookup.h:

#ifndef SubMaster_lookup_h
#define SubMaster_lookup_h

void func1(void);
void func2(void);

char LookupTable[][3]={ "00", "01", "02" "03", "04", "05", "06", "07", "08", "09",
"0a", "0b", "0c", "0d", "0e", "0f", "00", "01", "02" "03", "04", "05", "06", "07",
"08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", and so on...}

-

lookup.cpp:

#include "lookup.h"

void func1() {
   ...body of func1...
}

void func2() {
   ...body of func2...
}

The following structure gives me "ld: duplicate symbol _LookupTable" during build. Is there any way to change the structure, so it will not give errors?

like image 854
Jake Badlands Avatar asked Oct 25 '25 22:10

Jake Badlands


2 Answers

Two ways:

  • Declare the array in the header and define it in a cpp file
  • Make it static. But this is pretty nasty (each translation unit will get its own copy)

Try this:

lookup.h
extern char LookupTable[][3];

lookup.cpp
#include "lookup.h"

char LookupTable[][3] = ...

This answer is good.

like image 86
cnicutar Avatar answered Oct 28 '25 10:10

cnicutar


You can have extern char const lookupTable[][3]; in the header, and the actual implementation in a source file:

#include "header.h"

char const lookupTable[][3] = { /* ... */ }

Alternatively, declare the array as static char const lookupTable[][3] = /*...*/ in the header, but then you get repeated copies in each TU (each with static (i.e. internal) linkage).

like image 45
Kerrek SB Avatar answered Oct 28 '25 11:10

Kerrek SB