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:
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
The extern keyword in C and C++ extends the visibility of variables and functions across multiple source files. In the case of functions, the extern keyword is used implicitly. But with variables, you have to use the keyword explicitly.
You can initialize any object with the extern storage class specifier at global scope in C or at namespace scope in C++. The initializer for an extern object must either: Appear as part of the definition and the initial value must be described by a constant expression; or.
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);
}
Suppose if you declare within function:
// in file b.c:
void foo() {
extern int x;
printf("%d\n", x);
}
void foo_2() {
printf("%d\n", x); <-- "can't use x here"
}
then x
is visible locally inside function foo()
only and if I have any other function say foo_2()
, I can't access x
inside foo_2()
.
Whereas if you declares x
outside before all function then it would be visible/accessible globally in complete file (all functions).
// in file b.c:
extern int x;
void foo() { printf("%d\n", x); }
void foo_2() { printf("%d\n", x); } <--"visible here too"
So if you need x
in only single function then you can just declare inside that function but if x
uses in several function then declare x
outside all function (your first suggestion).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With