Mac,
I'm sorry, I should have given some examples.
I was trying to give informal definitions of the terms. Look "declaration" and "definition" up in you favorite C book for different wording.
A declaration just gives C just enough information to correctly reference a variable or function.
As in:
Code:
extern int foo; // declaration double sin( double arg ) ; // declaration
The compiler gets enough information to reference the variable or function, but it is up to the linker to find where the actual variable or the function body is.
A definition creates a definite place for a C variable or function and completely describes it. It includes all the information in a declaration, but has the additional information of the variable initial value or a function body
Code:
int foo ; // definition tells compiler "put foo here"// definition tells compiler "put the sin function here,// with this definitiondouble sin( double arg ) { /* much code */} ;
Actually gives the storage location or the function body.
bigmac wrote:
Hello Steve,
I am still a little confused over the declaration/definition issue for global variables. Let's assume that we only have one file, say main.c. From your previous comments, I presume that the following code would be necessary, outside of any function, to declare/define a single global variable global_var1.
int global_var1; // Declaration?
Actually a definition without an initializer given.
int global_var1 = 0; // Definition?
Yes, also a definition
void main(void)
{
etc.
Is this the correct interpretation of your previous explanation? Is it also allowable to combine the declaration and definition as a single assignment?
You can't avoid it. A definition includes all the information in a declaration, and more
Now I would assume that both the declaration and definition can only occur once in a program (there can only be a single initial value).
Its good practice to have only one declaration for an item in a module, but many are allowed, if they all agree.
So, for example if you have a declaration for a function in a header file, it is helpful to include that header file in the module that defines the function. The compiler will report an error if the header file declaration doesn't match the definition.
You can only have one definition of something global in a program.
However, if we now add a second file that references the same global variable, I have previously understood that we need to tell the compiler to look for the declaration of the variable elsewhere. So the new file would need to include the following prior to first use of the variable, and this would occur for all additional files that use the variable:
extern int global_var1;
You are correct. This is indeed a declaration