Most people seem to think that these two terms are inter-changeable: they are not! There is a very clear distinction between a variable definition and variable declaration.
A variable definition defines the variable to the compiler. In the process, it specifies the data type, storage class and initialization. Most importantly, a variable definition results in memory allocation by the compiler. Thus, a variable once defined can never be re-defined.
Examples of variable definition:
int x; int x=10; auto int x; register int x; static int x; extern int x=10;
A variable declaration merely declares the existence of a variable to the compiler and documents it’s data type. Thus, the compiler realises that there will be a variable of that name and data type defined elsewhere. The declaration does not result in any memory allocation, and hence declarations can be repeated multiple times without any problem, though there is no need to.
There is only one way a variable can be declared in C:
extern int x;
This declaration tells the compiler that there is a variable called x of type int which will be defined elsewhere (probably even in a different C program).
Summary: variable definitions result in memory allocation and cannot be repeated whereas variable declarations do not result in memory allocation and can be safely repeated.
Related questions:
Q: How do I compile multiple C programs and link them together?
Q: How can a variable defined in one program be used in another program?
Q: How can I prevent variables in different C programs from clashing when they are linked together?
Related Articles
No user responded in this post