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

2
  • This answers the same question for C++. There are differences between C and C++, but for what you ask they don't apply. Commented Jul 27, 2010 at 9: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. Commented Jul 27, 2010 at 10:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I pretty much just summarized The C Programming Language's material on the matter. Thanks, though.
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).
How is int i in 2nd case definition?? Is it due to the fact that it gets a garbage value; which is a defination??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.