Sunday 2 February 2014

How do I share a variable between source files in C? With `extern`, but how?

An extern variable is a declaration (thanks to sbi for the correction) of a variable which is defined in another translation unit. So that means that the variable is defined in another file...
Say you have two .c-files test1.c and test2.c. If you define a global variable int test1_var;in test1.c and you'd like to access this variable in test2.c you have to use extern int test1_var; in test2.c.
Complete sample:
$ cat test1.c 
int test1_var = 5;
$ cat test2
.c
#include <stdio.h>

extern int test1_var;

int main(void) {
printf
("test1_var = %d\n", test1_var);
return 0;
}
$ gcc test1
.c test2.c -o test
$
./test
test1_var
= 5

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More