Suraj Menon
Suraj Menon

Reputation: 1594

Extern code not working

Why aren't the codes below working ? Please explain.

#include<stdio.h>
#include<stdlib.h>

int main(int number, char arg[])
{
    extern int i;
    i = 5;
    printf("%d",i);
    return 0;
}

#include<stdio.h>
#include<stdlib.h>

int main(int number, char arg[])
{
    extern int i;
    i = (int) malloc(sizeof(int));
    i = 5;
    printf("%d",i);
    return 0;
}

Upvotes: 0

Views: 4838

Answers (4)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

When writing

extern int i;

you're simply declaring (but not defining) a variable named i. You need to define i somewhere in your program. For example, it could be just after main or in another .c file

int main(int number, char* arg[])
{
    extern int i;
    i = 5;
    printf("%d",i);
    return 0;
}
int i; //here you define i

Upvotes: 0

md5
md5

Reputation: 23699

The extern keyword provides, by default (whitout an initializer for instance), a declaration of the variable. You need to define your variable. To have an internal linkage:

#include <stdio.h>
#include <stdlib.h>

static int i;

int main(int number, char arg[])
{
    extern int i;
    i = 5;
    printf("%d",i);
    return 0;
}

And an external linkage:

#include <stdio.h>
#include <stdlib.h>

int i;

int main(int number, char arg[])
{
    extern int i;
    i = 5;
    printf("%d",i);
    return 0;
}

See also here.

C11 (n1570), § 6.2.2 Linkages of identifiers
For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

Upvotes: 0

tomahh
tomahh

Reputation: 13651

extern is used to specify that a variable exists, but is not yet defined. You do not create the variable, only specify to the compiler that it exists. If it does not, you will have an error at linking time.

I suggest you read more about extern keyword

A simple example of use would be two .c files, one with your extern variable as global, and one which prints this variable

file.c

int value = 5;

main.c

int main() {
  extern int value;

  printf("%i\n", value);
  return 0;
}

compiling this using gcc file.c main.c will output 5

Upvotes: 3

Afaq
Afaq

Reputation: 1155

Extern variable's values must be defined from outside the function in which they are defined.

Upvotes: 0

Related Questions