0% found this document useful (0 votes)
28 views

Extern Keyword

explanation of extern keyword for c programming

Uploaded by

Viraat Sewraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
28 views

Extern Keyword

explanation of extern keyword for c programming

Uploaded by

Viraat Sewraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 5
= 3G a ¢ Web Development Boots Trending Now ata Structures Algorthms Topicwise Practice Python Machine Learning DstaScience JavaScript save extern Keyword in C Read Diseussis80e) Courses Practice extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern keyword extends the visibility of the C variables and C functions. That's probably the reason why it was named extern. Though most people probably understand the ditference between the “declaration” and the “definition” of a variable or function, for the sake of completeness, ets clarity it + Declaration of a variable or function simply declares that the variable or function exists somewhere in the program, but the memory is not allocated for them, The declaration of a variable or function serves an important role-it tells ‘the program what its type is going to be. In the case of function declarations, it also tells the program the arguments, their data types, the order of those arguments, and the return type of the function. So that's all about the declaration + Coming to the definition, when we define a variable or function, in addition to everything that a declaration does, it also allocates memory for that variable or function. Therefore, we can think of the definition as a superset of the declaration (or declaration as a subset of the definition), + Extern is a short name for external * The extern variable is used when a particular files need to access a variable from another file, Syntax of extern in C ‘The syntax to define an extern variable in Cis ust to use the extern keyword before the variable declaration extern data_type vartoble_name; Example of extern Variable in C c D sinciude @ extern int a; // int var; -> declaration and definition 11 extern int var; > declaration > ant main) ‘ prinee(*xd", 995 return 95 y Properties of extern Variable in C ‘+ When we write extern some_data_type some_variable_name; no memory is allocated. Only the property of the variable is announces, ‘+ Multiple dectarations of extern variable is allowed within the file. This is not the case with automatic variables. + The extern variable says to the compiler “Go outside my scope and you will find the definition of the variable that | declared.” + The compiler believes that whatever that extern variable said is true and produces no error. Linker throws an ertor when it finds no such variable exists, ‘+ When an extern variable is initialized, then memory for this is allocated and it willbe considered defines. ‘A variable or function can be declared any number of times, but it can be defined only once. (Remember the basic principle that you can't have two locations of the same variable or function), Now back to the extern keyword. First, Let's consider the use of extern in functions. It turns out that when 3 function is. declared or defined, the extern keyword is implicitly assumed. When we write. o DE vases sae Programming - Complete Beginner toAdvonced IE Ant foo(int argi, char arg2); The compiler tre extern int foo(int angi, char arg2)3 Since the extern keyword extends the function's visibility to the whole program, the function can be used (called) anywhere in any of the files of the whole program, provided those files contain a declaration of the function. (With the declaration of the function in place, the compiler knows the definition of the function exists somewhere else and it goes ahead and compiles the file). So that’s all about extern and functions. Now let's consider the use of extern with variables, To begin with, how would you declare a variable without defining it? ‘You would do something like this: extern int vars Here, an integer-type variable called var has been declared [it has 50 far). And we can do this declaration as many times as we want. Now, how would you define var? You would do this: Ant var = 19; In this line, an integer type variable called var has been both declared and defined (remember that definition is the superset of declaration). Since ths is a definition, the memory for var is also allocated. Now here comes the surprise. When we declaredidefined a fun 7, we saw that the extern keyword was present implicitly. But this isn't the case with variables. fit were, memory would never be allocated for them. Therefore, we need to include the extern keyword explicitly when we want to declare variables without defining them, Also, as the extern keyword extends the visibility to the whole program, by using the extern keyword with a variable, we can use the variable anywhere in the program provided we include its declaration the variable is defined somewhere. Now let us try to understand extern with examples. Example ne nain(voie) t Dhaene: > ‘This program compiles successfully. var is defined (and declared implicitly) globally Example 2: extern int vars int main(void) « > ‘This program compiles successfully. Here var is declared only, Notice var is never used so no problems arise Example 3: c © extern int var; Ant matn(void) « var = 105, D return @ » ‘This program throws an error in the compilation(during the linking phase, more info here) because var is declared but rot defined anywhere. Essentially, the var isnt allocated any memory. And the program is trying to change the value to 10 of a variable that doesn't exist at at. Example c © 1/ as we are importing the file and henceforth the 11 éeFination 1/ vectaring the sane variable fxtern int vari 1/308 vars 11 XE wi throw compiler error as compiler will get 11 confused where the variable is defined int main(void) » 11 Now 3&1 compile and run successfully Output: 10 Note: Here arises another scenario what if we do not declare with extern in the above code snippet? Considering an assumption that somefile.h contains the definition of var this program will compile successfully. extern’ keyword is used for a variable when we declare the variable in one file and define itn another file. But here when we import the same file in the file where its declared, here compiler error will be generated. Its because we still have to use the extern keyword in the file where we have declared that variable so as to tell our ‘compiler that this variable is been defined somewhere else than only new memory space will not be allocated else it “will create another memory block which usage of ‘extern’ keyword useless. Example c D extern ine var nt: matn(void) Do you think this program will work? Well, here comes another surprise from C standards. They say that. fa variable is ‘only declared and an initializer is also provided with that declaration, then the memory for that variable will be allocated-in other words, that variable will be considered as defined. Therefore, as per the C standard, this program will ‘compile successfully and work, So that was a preliminary look at the extern keyword in C. In short, we can say: 4. A declaration can be dene any number of times but defined only once. 2. the extern keyword is used to extend the visibility of variables/functions, 3, Since functions are visible throughout the program by default, the use of the extern is not needed in function declarations or definitions. Its use is implicit. 4, When extetn is used with a variable, it's only declared, not defines. 5, As an exception, when an extern variable is declared with initialization. itis taken as the definition of the variable as well Last Upeated 06 May, 2023, Similar Reads Ea Name Mangling an extern "C"incr+ Ea Use ofexpliit keyword in c++ Ea ‘c++ mutable keyword Ea (c+ Static Keyword | Question 2 Ea + | fiend keyword | Question? < Previous Storage Classes in C Article Contributed By : 6 GeekstorGeeks oe O Ea Understanding "register" keywordin¢ Ea Function overleacingand const keyword Ea +t [Statickeyword| Question Ea 4 friend keyword | Question 1 Ea C+ | Static Keyword | Question + Next > Static Variables in € Vote for difficulty Ccurcen cificalty Mesum Improved By: Akanksha Ral, anupamgodsel21, NikHert, derekhullinger, solankimayank, harshlurra, surinderdawra38a, rushmunjewar, vivekedula, adityadav20102001, geathecode, abhishekcpp ArticleTags:_CKeyword, CStorage Classes and Type Qualifiers, C Language OG eeksforGeeks Company Legal nec Campus traning Program ‘Computer Science ‘GATE CS Notes operating Systems Computer Network Database Management system Sofware Engineering Digital Loge Design Engineering Maths Interview Corner ‘company Wise Preparation for SOE xperiened Interviews Intemshipinterviws ‘Aptitude Preparation Explore Job-AcThon Hiking Challenge fackea-thon te week conte oftine lasses DeNCR, OsAInsAVAICr® Mastersystem Design Masterce Python ython Programming Seamples Django Tutorial Python Projets Python Thinter ‘opency Python Tutorial Python interview question GfG School CCESENotee for Cla (CASE Notes forclas9 (CASE Notes or clas 10 (CBSE Notes for Clase22 (CBSE Notes for Class 12 agish Grammar ‘143, th Floor, Sovereign Corporate Tower, Sector136, Noi, Utar Pradesh © teedbackogeelstorgeetsorg GOO80 Ss os Languages seu Ranguage Data Science & ML Data Science With Python Mochi tearing Tutorial Leoring Pandas Tori NumPy Tato Deep Learning Tatar Commerce esountancy Business Studies Management Income Tax States for Economics DSA Concepts stings Linked ust searching sorting athena Dynamic Programming Devops ie ans Docker are ce upse Polity Notes Geoeraphy Notes Science and Technology tthies errr DSA Roadmaps DSA lor Beginners asic dA Coding Problems sa Roadmap by Sandeep Jin saith avascrint Al Chest sheets competitive Programming Top osaforce ‘Top soTree Problems “op 50 Graph Problems ‘op 50 ray Problems Top So sting Problems Top So DP Problems ‘Top 19 Websites or CP 'SSC/ BANKING SSC CL Syllabus 58170 sylabus soi cleksllabus aps Po sylabus 15s clerk sylabus Aptitude Questions SSC COL Practice Papers Web Development css savaSeript Bootstrap gues Nodess beressie System Design Whatis system Design Monoithicand Sealabitty in so Databaresin 0 High Level Designor Top sointervew ‘Questions Write & Earn Wotean atic Improve an Atle Pick Topestowrite Write tersew

You might also like