Hi,
One of my assignment questions is to write a program to illustrate external storage class, extern variable,global variable and thus write the differences between global variable and external variable.

My program :

#include <stdio.h>
extern int i;

int main()
{
printf("\n%d",i);
inc();
dec();
getch();
return 0;
}

inc()
{
i++;
printf("\n%d",i);
return 0;
}

dec()
{
i--;
printf("\n%d",i);
return 0;
}

Which is supposed to give the output

0
1
0

My compiler reports an error : "Undefined symbol _i"

I'd like to know the mistake in the program and in the usage of extern variable.


Thanks a lot for your time.

Recommended Answers

All 3 Replies

The extern keyword tells the compiler that the symbol (in this case i) is located in an external module. In simple words, in another source file. In another source file, declare the variable i as you normally would declare a global variable.

yes, U need another source file with int i defined in it.

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.