Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extern in multiple files and possible double definition

I was running the following codes compiled together as: gcc A.c B.c -o combined

Program A:

#include<stdio.h>
int a=1;
int b;
int main()
{
extern int a,b;
fun();
printf("%d %d\n",a,b);
}

Program B:

int a;
int b=2;
int fun()
{
printf("%d %d\n",a,b); 
return 0;
}

On running the "combined" program the output was:

1 2
1 2

Now, I've a few doubts about this one:

  1. Why isn't the output:

    0 2

    1 0

  2. Aren't a and b defined twice?

Please explain these clearly, I've had a lot of problems understanding extern and few of these doubts keep coming from time to time.

Thanks in Advance.

like image 375
tapananand Avatar asked Jul 01 '13 04:07

tapananand


People also ask

Is extern int i declaration or definition?

extern int i; is a declaration (no memory allocation), while. int i; is a definition (memory is allocated). Aren't both statements only declaring a variable i as an int , only that one specifies that it's a global variable?

Does extern make a variable global?

The extern keyword may be applied to a global variable, function, or template declaration.

What is difference between extern and global?

Global variable is a variable that is available throughout the program. An extern variable is also available throughout the program but extern only declares the variable but it doesn't allocate any memory for this variable. It means you can't ise the variable till you define it.

Does extern allocate memory?

The extern keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition. So in file2 , you just declared the variable without definition (no memory allocated).


1 Answers

A variable may be declared many times, as long as the declarations are consistent with each other and with the definition. It may be declared in many modules, including the module where it was defined, and even many times in the same module.

An external variable may also be declared inside a function. In this case the extern keyword must be used, otherwise the compiler will consider it a definition of a local variable, which has a different scope, lifetime and initial value. This declaration will only be visible inside the function instead of throughout the function's module.

Now let me repeat again definition of extern which says "external variable is a variable DEFINED outside any function block"(Please read carefully word given in BOLD). So for the Programe A a have definition but b is just declaration so extern will look for its definition of 'b' which is given in Programe B.So print from Programe A is 1 2.Now lets Talk about Programe B which have declaration for a and definition for b so it is priting value of a from programe A and value of b from current file.

like image 138
Dayal rai Avatar answered Oct 19 '22 03:10

Dayal rai