fnord_disc
fnord_disc

Reputation: 3

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.

Upvotes: 0

Views: 268

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222900

Put the declaration in a header file:

extern short KM[72][3][3][3][3][3][3];

Put the definition in a source file:

short KM[72][3][3][3][3][3][3] = { … };

To define just certain elements to be non-zero, use designated initializers:

short KM[72][3][3][3][3][3][3] = {
    [37][1][1][1][2][2][0] = 4,
    …
};

If there is a run of consecutive non-zero elements, you can designate the first one and list the following ones:

short KM[72][3][3][3][3][3][3] = {
    [37][1][1][1][2][2][0] = 4, 5, 6, 9, 3,
    …
};

(A compiler might warn you about this, and that would be an acceptable warning to disable in this situation.)

Include the header in any source file that uses the array, including the one that defines it.

Compile the source file that defines the array and include it when linking the program.

Only declarations (including definitions) and preprocessor statements can be outside functions. Assignment statements such as KM[0][0][0][0][0][0][0] = 0; may appear only inside a function.

Upvotes: 0

perreal
perreal

Reputation: 97958

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.

Upvotes: 1

Related Questions