2

Still confused with declaration and definition in term of C: if a header file is like:

#ifndef _BASIC_H_
#define _BASIC_H_

void test();
extern int i; //define or declare
#endif

and two source file f1.c and f2.c contain this header, then one source file need to define the variable "i".

but if the header file is like:

#ifndef _BASIC_H_
#define _BASIC_H_

void test();
int i; //define or declare
#endif

and two source files f1.c and f2.c, contain this header without define the variable "i" in any file, it still goes through when I use the variable.
my questions is when the variable is defined.

Thanks

Alfred
  • 1,709
  • 8
  • 23
  • 38
  • [This answers the same question for C++.](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration/1410632#1410632) There are differences between C and C++, but for what you ask they don't apply. – sbi Jul 27 '10 at 09:35
  • Note that `void test();` is not the same as `void test(void);`. The second one will catch errors where you call `test(foo);` at compile time. – nmichaels Jul 27 '10 at 10:47

1 Answers1

8

Defining a variable is when you allocate memory for the storage and maybe assign it a value. Declaring is when you state that a variable with a specific name and type exist, but memory has been allocated for it already.

The use of the extern keyword means that you are declaring the variable but not defining it.

In terms of your specific question, your first example is declaring and your second answer is defining.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
  • I pretty much just summarized The C Programming Language's material on the matter. Thanks, though. – Thomas Owens Jul 27 '10 at 09:44
  • 2
    Note that '`int i;`' gives a definition of the variable. The strict reading of the C standard says that if more than one file includes that header, then you will get multiple definitions for `i`, and the link phase of the compilation will fail. Appendix J (§J.5.11), gives a 'common extension' as: **Multiple external definitions** There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword `extern`; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2). – Jonathan Leffler Jul 27 '10 at 22:20
  • How is int i in 2nd case definition?? Is it due to the fact that it gets a garbage value; which is a defination?? – Raj Kumar Mishra Oct 23 '17 at 04:49