blogger Indonesia

Follow judhyns blog

EXTERNAL REFERENCES

Introduction

In collaborative software development it is common for multiple users to write programs in different files. For example, one user implements function f1, a second user implements function f2, while a third user implements the main function. C has a provision to compile programs even if function or variable implementation is not available. In such cases, the program is compiled but it is not yet fit for execution. The program is not executable until all the references in the file are available.

Program

\\ Program in file externa1.c  #include                  \\ A #include  \\ B extern int i;                            \\ C main() {     i =0;                                            \\ D     printf("value of i %d\n",i); }  \\ Program in file f1.cpp  int i =7;                                       \\ E 

Explanation

  1. Here the program is written in two files: extern1.c and f1.cpp. The file extern1.c has the main and reference of variable i.

  2. The file f1.cpp has the declaration of i.

  3. In the file extern.c there is a reference of i so the compiler should know the data type of i. This is done using the extern definition by statement C. Extern means that the variable or function is implemented elsewhere but is referred to in the current file.

  4. Statement D refers to i.

  5. The definition of i is given in the file f1.cpp, as given by statement E.

  6. In the absence of an include directive in statement B, you can still compile the file; it will give no errors. Such a file is called an object file. It is not fit for execution because the reference of i is not resolved.

  7. When you write statement B the reference of i is re-sorted and the executable file can be made.

Points to Remember

  1. Extern definition is used when you have to refer a function or variable that is implemented elsewhere or it will be implemented later on.

  2. When all the references are resolved then only the executable file is made.


No comments:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |