0

I have a header constants.h file, with the following declarations of an array variable:

extern storageCommandData storageCommands[];

The type of the array is defined elsewhere, and is not relevant to the question. In another source file (.c) I initialized the array like so:

#include "constants.h"

storageCommandData storageCommands[STORAGE_COMMAND_NUM] =
    {
        /*storageCommandData intilazation follows the
          following template: {commandName, storageSize}*/
        {".db", 1},
        {".dw", 4},
        {".dh", 2},
        {".asciz", 0},
};

I tried to use these arrays in another source file (a different one than the one I define the arrays in), by including constants.h.

However, when I try to use the variable storageCommands I get the following error message:

undefined reference to `storageCommands'

How do I fix the error?

Jens
  • 69,818
  • 15
  • 125
  • 179
Itai Elidan
  • 272
  • 9
  • 27
  • 5
    When linking, did you include the source or object file containing the definition of `storageCommands`? Please show the command lines you used to compile and link, or otherwise explain your build process. – Nate Eldredge Aug 13 '21 at 19:20
  • 1
    Including the .h file in the other file is not enough. You need to link it with the object file containing that array – 0___________ Aug 13 '21 at 19:21
  • Please read [this](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) first. – n. m. could be an AI Aug 13 '21 at 19:23
  • Thank you, that was the answer. I didn't link the source file that defined the arrays when I compiled – Itai Elidan Aug 13 '21 at 19:23
  • The name "constants.h" sees to promise something you may not be delivering (unless the typedef `storageCommandData` includes a `const` qualifier). If it is not truly a `const` then being global is a bad idea: https://www.embedded.com/a-pox-on-globals/ – Clifford Aug 13 '21 at 19:43

1 Answers1

1

Using extern means that you are using a variable that is declared in another translation unit (i.e. basically a source file and the headers it includes). It is the linker's task to relate the extern-specified variable name to its actual declaration. If the linker cannot find the latter, it will report an "undefined reference".

As already pointed out in the comments, the most common cause of this error is that the source file containing the actual declaration was not compiled or linked.

Yun
  • 3,056
  • 6
  • 9
  • 28