Thread: External variable in c language

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    10

    External variable in c language

    Extern keyword tell to compiler that this variable is declared in another C file but we can use it in current file

    Lets say we have two files
    File1.c
    File2.c

    First method
    I have declared x in file 1 and if i want to use x in file 2 I can use but I have to use extern keyword in file 2 to tell the compiler that variable x is already in file 1

    Code:
    File1.c 
    
    int x;
     
    int foo(void)
    {
        ...
    }
    
    
    File2.C 
    
     extern int x;
     
    int main(void)
    {
        x = 5;
        ...
    }
    Second method

    I have declared x in file 1 and if i want to use x in file 2 I can use but I have to use extern keyword in file 1 to tell the compiler that variable x is already in file 1
    Code:
    File1.c 
    
    extern int x;
     
    int foo(void)
    {
        ...
    }
    
    
    File2.C 
     
      int x;
     
    int main(void)
    {
        x = 5;
        ...
    }
    which one is correct method to use extern variable in c file ?
    Last edited by skyr6546; 2 Weeks Ago at 04:54 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,264
    Both are correct. I mean, you're just regarding one file as the "first" and the other as the "second", then swapping over the designations in the next example.

    A more common way of doing this is to place the extern declaration in a header that is then included as needed.

    That said, you should avoid global variables, i.e., it should be rare that you even need to use this at all.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Declaration and definition of an external variable.
    By Mr.Lnx in forum C Programming
    Replies: 3
    Last Post: 01-12-2014, 03:02 AM
  2. external variable
    By sharonch in forum C Programming
    Replies: 5
    Last Post: 02-07-2013, 11:47 AM
  3. Replies: 8
    Last Post: 02-14-2010, 04:14 PM
  4. Access restriction for external variable..
    By bhupesh.kec in forum C Programming
    Replies: 4
    Last Post: 07-11-2008, 04:01 AM
  5. external variable
    By OnionKnight in forum C Programming
    Replies: 11
    Last Post: 12-24-2005, 09:50 AM

Tags for this Thread