Linkage, Scope of Variables and Functions in C

This C Tutorial explains Linkage/Scope of variables and functions in C with examples and defines the type of Linkages.

Linkage of any variable and/or function defines the Area of the Program in which they are accessible. There are three types of Linkages for the variables & functions. These are as follows

1. EXTERNAL
2. INTERNAL
3. NONE

External linkage defines that the variable, function can be accessed throughout the program, across the multiple source files if program comprises of several source files with the use of Keyword extern.

#include <stdio.h>
int counter;		    
extern float marks;
 
/*
 * External linkage: counter is an integer accessible across entire program	
 * External linkage: marks which is of float type defined in some other source file & used here
 */
 
void hello(void);
int main()
{
    printf("the marks are %f\n", marks = 55.9);
 
    return 0;
}

Static Keyword changes Linkage from External to Internal meaning that any variable, function declared globally with static keyword can only be accessed within the source file from the point of declaration until the end of the program in which it is declared.

advertisement
advertisement
#include <stdio.h>
 
/*
 * Internal Linkage: counter can only be accessed within this source file from this point till the end of the file
 * Internal Linkage: function hello can only be accessed within this source file
 */
 
static int counter; 			
static void hello(void); 		 
 
int main(void)
{
    hello();
}

Automatic and register variables neither have external nor internal linkages. They are accessed only within the blocks in which they are declared. For example:

#include <stdio.h>
void hello(void);
int main(void)
{
    hello();
 
    return 0;
}
 
void hello()
{
    int counter = 1;  /* counter is an automatic variable i.e. ONLY accessible within this block! */
 
    printf("the value of counter is %d\n",counter);
}

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.