This answer confused me.
If we have two lines in same .c file:
extern int c;
int c;
- How is the first line of code a declaration and second a definition?
- Aren't both declarations?
- How these two lines differ?
This answer confused me.
If we have two lines in same .c file:
extern int c;
int c;
The extern
keyword is what makes the first line a declaration. It say "this variable exists somewhere". A line like that can appear in a header file.
The second line is a definition because the extern
keyword is not present. If you were to have this line in a header file, two source files that include that header will both define that variable and linking those two files will result in a variable redefinition error.
When the program you're writing consists of multiple source files linked together, where some of the variables defined, for example, in source file file1.c need to be referenced in other source files, so this is the reason why using extern.
About your question how these lines differ:
extern int c;
int c;
A variable is defined when the compiler allocates the storage for the variable while
A variable is declared when the compiler is informed that a variable exists (and this is its type); it does not allocate the storage for the variable at that point.
so only int c;
is defined while extern int c;
is declared .
Long story short, defining something means providing all of the necessary information to create that thing in its entirety. However, declaring something means providing only enough information for the computer to know it exists.
Edit: To be clearer: A definition both defines and declares, a declaration ONLY declares. When you are using the extern
keyword by definition you are not defining anything. Your confusion stems from the understanding of extern
.
A definition creates space for a variable:
int c;
Wherever you put this line, either local, global, this says that a new variable c
of type int
shall come to life.
extern int c;
A declaration says that there is somewhere else some variable c
of type int
. By using extern
, you say that c
is defined somewhere else. If you put only an extern
declaration without a definition somewhere else, you will have a link error. Using extern is the equivalent of a forward declaration of a function:
/* declaration */
int f(int x);
vs.
/* definition */
int f(int x) {
return x*x;
}
The first means that there is somewhere a function f
returning an int
and accepting an int
as parameter. The latter is the actual function, its code, which also works both as a declaration and a definition.
IMO, this declaration-vs-definition naming is confusing. I hardly remember which one is what, and I usually need to think about it. You should, however, understand the what extern
means and what a forward declaration is.