Search code examples
cglobalexternalextern

Defining external variable externally


I've been looking around for a solution to this and despite the code fragments and explanations on SO and elsewhere it doesn't seem to work. What I want is to define a very large array externally so it doesn't clutter up the code and use the definition in my main file.

It's really quite simple:

controller.h defines the variable:

short KM[72][3][3][3][3][3][3];
KM[0][0][0][0][0][0][0] = 0;
KM[1][0][0][0][0][0][0] = 0;
KM[2][0][0][0][0][0][0] = 0;
// ...
// 50.000 more lines, not all =0

And I expected this to work in main.ino:

extern short KM; // or KM[72][3][3][3][3][3][3], tried a lot
#include "controller.h"

void loop() {
...
}

But it doesn't ("controller.h: [...] error: 'KM' does not name a type"). All I want is the values sequestered in controller.h to be usable in main.ino.

I'm using the Arduino IDE and an ESP32.


Solution

  • You can't initialize the array with multiple statements like that. Try to use something like:

      short KM[72][3][3][3][3][3][3] = {
        0, 0, ...
      };
    

    or use a function:

    void initKM(short KM[72][3][3][3][3][3][3]) {
        KM[0][0][0][0][0][0][0] = 0;
    }
    

    Also you should define KM in a source file (controller.c?) and have the extern in the header file so that if you share the header there will be a single definition of KM.

    Note that I'm not really trying to nail down the syntax but rather give you an idea of how you can implement this.

    See this answer for correct initialization syntax.