Sharing a variable between two c files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinnejeevansai
    New Member
    • Nov 2014
    • 48

    Sharing a variable between two c files

    I am trying to share a variable between two c files

    common.h

    Code:
    extern char seq2[1000000];
    File1.c

    Code:
    #include "common.h"
    
    char seq2[1000000] = {0};
    void main(){}
    File2.c

    Code:
    #include "common.h"
    
    int main(){
    
    	if(seq2[0] != '.'){
    	  int j = 1;
    	  val = seq2[j-1];
    	  seq2[j-1] = '.';
    	}
    }

    and i am compiling the files like

    gcc File1.c -o f1
    gcc File2.c -o f2


    but i am getting error undefined reference to `seq2'.Can someone explain my mistake i tried multiple method on internet but none works.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    seq2 is an array.

    This code defines the array:

    Code:
    char*seq2[1000000]*=*{0};
    so every time you include this line you get a new array. The compile dies with multiple definitions.

    What you do is put this line of code in a .c file so the array is defined only once. Use the extern.

    Next, since this is an array, the name of the array (seq2) is the address of seq2[0]. Since seq2 is an array of char, the name seq2 is the address of a char. Put this in your common .h:

    Code:
    extern char* seq2;
    Notice you have lost the size of the array in common.h. This is called decay of array. More info here about arrays: https://bytes.com/topic/c/insights/7...rrays-revealed

    I suggest you add an int variable to the file that defines the array and initialize it to the sizeof the array. Then add this variable to your common.h so other files can see the address of the array and the size.

    BTW: This seq is an array of a million chars. It is defined as a local stack variable. Some C compilers limit the size of the stack to as little as 4096 bytes. I suggest you allocate the array dynamically using malloc() so all that's on the stack is the address of the allocation.

    You would need to allocate the array in main() before using it.

    Comment

    Working...