By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,661 Members | 781 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,661 IT Pros & Developers. It's quick & easy.

Sharing a variable between two c files

P: 48
I am trying to share a variable between two c files


Expand|Select|Wrap|Line Numbers
  1. extern char seq2[1000000];

Expand|Select|Wrap|Line Numbers
  1. #include "common.h"
  3. char seq2[1000000] = {0};
  4. void main(){}

Expand|Select|Wrap|Line Numbers
  1. #include "common.h"
  3. int main(){
  5.     if(seq2[0] != '.'){
  6.       int j = 1;
  7.       val = seq2[j-1];
  8.       seq2[j-1] = '.';
  9.     }
  10. }

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.
Jun 5 '17 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,197
seq2 is an array.

This code defines the array:

Expand|Select|Wrap|Line Numbers
  1. 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:

Expand|Select|Wrap|Line Numbers
  1. 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:

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.
Jun 5 '17 #2

Post your reply

Sign in to post your reply or Sign up for a free account.