I define a variable in a C file: int x
, and I know I should use extern int x
to declare it in other files if I want to use it in other files.
My question is: where should I declare it in other files?
Outside of all functions,
// in file a.c:
int x;
// in file b.c:
extern int x;
void foo() { printf("%d\n", x); }
within the function(s) that will use it?
// in file b.c:
void foo() {
extern int x;
printf("%d\n", x);
}
My doubts are:
Both are correct.
Which one is preferred depend on the scope of variable's use.
If you only use it in one function, then declare it in the function.
void foo()
{
extern int x; <--only used in this function.
printf("%d",x);
}
If it is used by more than one function in file, declare it as a global value.
extern int x; <-- used in more than one function in this file
void foo()
{
printf("in func1 :%d",x);
}
void foo1()
{
printf("in func2 :%d",x);
}