0

I've made a global variable for an array that's used in two files. We'll call them file1.c and file2.c, the variable is defined in a header file that both of them use, I'll call this file shared.h.

The variable is defined as int items[100]; in shared.h.

The main is in file1.c, and it calls functions from file2.c, the main will first initialize all values in the array with -1.

for(i = 0; i < 100; ++i){
   items[i] = -1;
}

Now, when I call a function from file2.c that uses items, i've noticed that all values in the array are reset to 0 instead of -1.

My question is why is the global variable re-initializing?

User9123
  • 675
  • 1
  • 8
  • 20
  • 3
    Don't define the array in the `.h` file. Define in one, **and only one**, `.c` file, add `extern` to the **declaration** in the `.h` file. Better yet, do not use globals and pass a pointer around. – pmg Apr 04 '21 at 17:46
  • Does this answer your question? [What is external linkage and internal linkage?](https://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage) – Brian61354270 Apr 04 '21 at 17:47

1 Answers1

1

why is the global variable re-initializing?

You have two different arrays with the same name. One with -1, the other with 0.

//foobar.h
extern int array[100]; // <== declaration

//foo.c
#include "foobar.h"
int array[100]; // <=== definition

//bar.c
#include "foobar.h"
pmg
  • 106,608
  • 13
  • 126
  • 198