Wednesday, March 28, 2018

Write a C++ program to illustrate storage classes-EXTERN


AIM: Write  a C++ program to illustrate storage classes-EXTERN

THEORY:
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
 int count ;
extern void write_extern();

main() {
   count = 5;
   write_extern();
}
Second File: support.c
#include <stdio.h>

extern int count;

void write_extern(void) {
   printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it produces the following result −
count is 5

SOURCE CODE:
#include<iostream>
#include"exe2.cpp"
using namespace std;
int count;
extern void write_exteren();
int main()
{
            count=5;
            write_extern();
            return 0;
}

Exe2-
#include<iostream>
using namespace std;
extern int count;
extern void write_extern(void)
{
            cout<<"count is:"<<count<<endl;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home