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;
}
externis 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
.cfiles, one with your extern variable as global, and one which prints this variablefile.c
main.c
compiling this using
gcc file.c main.cwill output5