6.4 — Introduction to global variables

In lesson 6.3 -- Local variables, we covered that local variables are variables defined inside a function (or function parameters). Local variables have block scope (are only visible within the block they are declared in), and have automatic duration (they are created at the point of definition and destroyed when the block is exited).

In C++, variables can also be declared outside of a function. Such variables are called global variables.

Declaring and naming global variables

By convention, global variables are declared at the top of a file, below the includes, but above any code. Here’s an example of a global variable being defined:

The above example prints:


By convention, many developers prefix global variable identifiers with “g” or “g_” to indicate that they are global.

Best practice

Consider using a “g” or “g_” prefix for global variables to help differentiate them from local variables.

Global variables have file scope and static duration

Global variables have file scope (also informally called global scope or global namespace scope), which means they are visible from the point of declaration until the end of the file in which they are declared. Once declared, a global variable can be used anywhere in the file from that point onward! In the above example, global variable g_x is used in both functions doSomething() and main().

Because they are defined outside of a function, global variables are considered to be part of the global namespace (hence the term “global namespace scope”).

Global variables are created when the program starts, and destroyed when it ends. This is called static duration. Variables with static duration are sometimes called static variables.

Unlike local variables, which are uninitialized by default, static variables are zero-initialized by default.

Global variable initialization

Non-constant global variables can be optionally initialized:

Constant global variables

Just like local variables, global variables can be constant. As with all constants, constant global variables must be initialized.

Related content

We discuss global constants in more detail in lesson 6.9 -- Sharing global constants across multiple files (using inline variables).

A word of caution about (non-constant) global variables

New programmers are often tempted to use lots of global variables, because they can be used without having to explicitly pass them to every function that needs them. However, use of non-constant global variables should generally be avoided altogether! We’ll discuss why in upcoming lesson 6.8 -- Why (non-const) global variables are evil.

Quick Summary

6.5 -- Variable shadowing (name hiding)
6.3 -- Local variables

273 comments to 6.4 — Introduction to global variables

  • Lucas

    Sorry if this might be a silly question but I didn't get when Alex said, "While this is simple (and fine for smaller programs), every time constants.h gets #included, each of these variables is copied into the including code file. If constants.h gets included 20 times, each of these variables is duplicated 20 times".

    For me, because of the head guard on the top of the .h file,  any attempt to #include after the first one will not cause any harm because the compiler will simply ignore the content between the #ifndef and #endif once whatever the name you'd given to file is already defined. Thus, all those consts won't be defined more than once. I know I'm wrong but I just can't find where I'm mistaken.

    • Alex

      Not a silly question, this is a common point of misunderstanding.

      Header guards prevent a header file from being included more than once into a single file.

      Header guards do NOT prevent a header file from being included exactly once into multiple files!

      Thus, if you have a header called constants.h, and you #include constants.h into a.cpp, b.cpp, and c.cpp, you'll end up with 3 copies of constants.h, one in each file. Under normal circumstances, this isn't a problem. However, in this particular case, it can be a bit wasteful.

  • Jim

    This lesson is a quite confusing since it is not clear what you are calling a file.  Since you introduced us to multi files some time ago and just called then files. Now in this lesson you make reference to files and you've also used (NAMED).cpp. Can we safely say they are one and the same?

    With this in mind is it true that one or several xxx.cpp files can be put together to make a Program?

    Now when you speak of global (Static-Internal)variable is it true that they can only be used within a given xxx.cpp file where they were initialized in.  T/F ?

    When you speak of external variables is it true that they can be used in the xxx.cpp they were initialized in. And any other xxx.cpp file that is put into the same program.  T/F ?

    External variables can not be used in two different Programs. T/F ?

    • Alex

      Yes, by files I generally mean your code (.cpp) files. Yes, you can put one or several .cpp files together into a program.

      > Now when you speak of global (Static-Internal)variable is it true that they can only be used within a given xxx.cpp file where they were initialized in. T/F ?

      True. Internal variables are only accessible in the file in which they are defined.

      > When you speak of external variables is it true that they can be used in the xxx.cpp they were initialized in. And any other xxx.cpp file that is put into the same program. T/F ?

      True. However, the other files must "import" them via extern.

      > External variables can not be used in two different Programs. T/F ?

      True. A variable defined in one program can't be used in another without redefining it.

  • Did u forgot the const keyword when defining g_y in the above example?

  • Typo:
    In Summary section
    "By default, non-const global variables have external linkage by default.
    By default, const global variables have internal linkage by default."

    "By default" repeated in both sentences.

  • Shijian


    I am a little confused about the difference between global symbolic constants and global const variables.

    The scope, duration and linkage of global symbolic constants are the same as the global const variables?

    In your examples about global symbolic constants, it seems that they are not global variables because they are defined in a block.


    • Alex

      A symbolic constant is just another name for a const variable, so a global symbolic constant is the same thing as a global const variable.

      Putting variables in a namespace does not affect whether they are global vs local, it just affects how you access them (using the scope resolution operator ::).

      In the above example, the namespace itself is declared in the global area, so it is a global namespace, and all variables inside it are therefore global.

      • Shijian


        Thank you for your reply.

        I have one more question. You know, the global variable is defined outside the block. However,

        namespace Constant{

        // define const here


        is a block since it begins with "{" and ends with "}". So, based on the definition of global variable, the const inside namespace should not be the global variables because they are defined inside a block.

        Also, as you mentioned, if the symbolic const are global, it seems they are created only once when the program begins. So, in your example about symbolic const, I think it does not matter if we directly insert the code

        namespace Constants
            const double pi(3.14159);
            const double avogadro(6.0221413e23);
            const double my_gravity(9.2); // m/s^2 -- gravity is light on this planet
            // ... other related constants

        in each file, since these variables are only defined once at the beginning of your program not matter how many times we copy the above code. So it will not induce the memory problem.

        • Alex

          Although blocks do start and end with curly braces, this doesn't mean that everything in C++ that uses curly braces is a block. The curly braces for namespaces don't define a block -- they're just used to enclose the declarations inside the namespace.

          > Also, as you mentioned, if the symbolic const are global, it seems they are created only once when the program begins.

          This is true.

          Remember that by default, const variables are static, and have file scope. When you paste the Constants namespace into multiple files, you're creating a separate (file-scoped) variable (with the same name) in each file.

          To be clear:



          foo and goo each have a (separate) file-scoped global variable named pi. Each pi variable has its own memory, and gets initialized once, at the beginning of the program.

          If you want to have one pi variable shared across multiple files, then you'd have to do this:



  • Siri_Noob


    While this is simple (and fine for smaller programs), every time constants.h gets #included, each of these variables is copied into the including code file. If constants.h gets included 20 times, each of these variables is duplicated 20 times...

    I Don't get it! Header guards aren't working?? Why should i have to do the other way with forward declaration?
    Thanks Once again!

    • Alex

      Header guards prevent a header from being #included into a single code file more than once.

      The do _not_ prevent a header from being included into multiple different files one time each.

  • cpplx

    im thinking of those endless chains of pointers leading to pointers leading to pointers leading to pointers....
    the last example in the lesson... forward declaration in .h, definition in .cpp... were not the .cpp files included by default in a project? or the example is assuming an external file?

    and talking about the endless chain... how long is too long? and if that was a person going from office to office just to get departed to the next office... that would be outrageous... does the compiler have problem with that? and I assume the compiled executable is not going through that chain, right?

  • Shivam Tripathi

    so it means that if i define a new variable of same name which is in another file then the new variable will shadow that variable from another file...correct??
    and if we want to use that same variable by "include" -ing that file...then we hv to use extern keyword in order to make a reference that we r using the same variable frm that another i right??...:)

    but alex one thing is bothering global.cpp i made sm changes...i defined variables as "static int g_x".and "static int g_y" by giving both of them value 2..and then #include that global.cpp in main.cpp..
    now in main.cpp..i cout g_x & g_y...nd i got the output of 2 if it was static then why it gave output in another file?? shud be linked to that translation unit only...??

    • Alex

      > so it means that if i define a new variable of same name which is in another file then the new variable will shadow that variable from another file…correct??

      No, there's no shadowing in this case. Because both variables are static, they have internal linkage. So neither variable is aware of the other's existence, and because their scopes do not overlap, there is no conflict.

      > and if we want to use that same variable by "include" -ing that file

      You shouldn't #include .cpp files in other .cpp files. You probably won't get the results you expect. By defining static int g_x in global.cpp, you've made that variable file scope. However, by #including global.cpp in main.cpp, you copied the contents of global.cpp into main.cpp, and that includes the definition for static int g_x -- so now main.cpp has a static int g_x as well.

      In short, you don't need to use #include at all to use a global variable from another file. Just declare the global in one file, and then use a forward declaration in another file to use that same global there. The linker will connect the two.

      • Shivam Tripathi if u wanna use that just make it's forward declaration...the linker will automatically link it..
        i got my mistake too...i was always thinking of #include" -ing those files and then trying to analyze the output..infact linker links the variables automatically...and there comes the usage of "extern"..which confirms that the variable is from another translation unit and can be used in any other file where it has got its forward declaration...whereas the "static" one if referenced in any other file will give error coz it is linked to that particular file i right???

          • Shivam Tripathi

            okk..thank u so much alex...just one last query.

            Why use this "extern" specifier ....why not just #include the content of one file in any other file...just make some files containing d proper declarations nd definitions and #include them in the main()...will it make any difference???

            And if u say dat it's not a proper thing to do...then u are requested to tell me the same wid reasons and also tell d difference b/w both the methods and also the feasible method between both of them with satisfactory reasons..plzz...:)

            • Alex

              #include just copies the contents of the included file into the including file before compiling it. It doesn't do anything else. That's great for ensuring declarations propagate, so the compiler can see how things are declared, but does not alter the scope of anything.

              If you define a variable in a .h file (which you shouldn't do) and then include that .h file in two different .cpp files, you now have two independent versions of that variable (one in each file).

              Extern is used to tell the compiler that one of those variables is the same as the other so the compiler doesn't throw an error about multiple definitions for the same variable.

      • dex

        Hi Alex, thanks for creating this tutorial. I learned a lot. :)

        I was just confused in this comment. As I understand, Mr. Shivam removes the extern keyword in the main.cpp. which your are definitely correct that it will define new variables named g_x and g_y in main.cpp. In global.cpp, g_x and g_y were also defined, compiling this, it will produced an error of "multiple definitions of g_x" since they are of the same variable name, their scope is global and by default they are both external because both of the variables are non const. Am I understanding it correctly?

        Thanks again. :)

        • Alex

          Here's the short of it:

          If a global variable with the same name is defined in two (or more) different files:
          * If the variable has internal linkage (e.g. is static, or constants), it will not collide. Each file will have its own copy of the variable.
          * If the variable has external linkage, it will have a naming collision with the variables in the other files (that also have external linkage), and this will cause a multiple definitions error.

          There was no collision in Shivam's case, because his variables were declared as static.

  • Shivam Tripathi

    hii alex...ur tutorials are just awesome..m really enjoying has helped me a lot so far...:)
    i hv a li'l bit confusion regarding linkage concept...i searched a lot on web about it but that didn't satisfy me..moreover in context to ur example given above which tells the forward declaration of variable using "extern", i hv a confusion...
    actually i ran the same code "global.cpp" & "main.cpp" and i didn't use extern keyword ..yet the program was working correctly and was giving the expected and desired output...and i was able to manipulate those variables values without any problem..
    my quest is that how can it be extern keyword necessary.or we can skip it...plzz help me out..:)

    • Alex

      Yes, you must use extern to use a variable defined in one file in another file. Without it, you'll define a new variable of the same name.

      Since you removed the extern keyword, what happened is your main.cpp defined new variables named g_x and g_y instead of using the same g_x and g_y that were defined in global.cpp.

  • Todd


    "Similarly, in order to use a (an) external global variable"

  • 1915

    I’m really new to coding, so I apologize if this is a stupid question, but I’m getting a little confused.

    Looking at constants.cpp and constants.h, it seems like you’re defining two different namespaces with the same name, "Constants." If in the code file you write:

    which namespace will the compiler look into for "pi"? If it looks into the header file and sees the forward declaration for pi, I’m guessing that redirects it to constants.cpp to find pi’s definition… but is there any conflict that occurs because it will encounter two namespaces with the same name along this path?

    • Alex

      Namespaces can be split across multiple files, with all of the content considered part of the same namespace. So the content defined in constants.cpp is considered part of the same namespace as the content in constants.h, even though the definitions are split across multiple files.

      This allows us to separate out the forward declarations from the definitions, while keeping both in the same namespace.

      • 1915

        Ahh, I see; thank you for your help! After I posted that, I was able to read up to the page on namespaces (4.3a) and I thought that might be the case.

        Thank you for this awesome website! Your guide has been extremely useful, and I appreciate all of your hard work!

  • Matheus Ronfim

    Just to make sure, when you stated that "By default, non-const variables declared outside of a block are assumed to be external, and const variables declared outside of a block are assumed to be internal."
    isn't it the other way around? non-const variables are internal and const variables are external? because in the example above, you have the non-const as internal and the const as external:

    I was just a little confused, not sure if you did this intentionally or not. Thanks.

    • Alex

      The statement is correct. The examples above are intended to show how the keywords can be used to change the default state.

      To clarify:

      We can use the static and extern keywords to override the defaults

      I'll clarify the examples above because I can see how this is confusing.

  • Cevher Bilger

    In your last topic, "Global symbolic constants"; you say "If constants.h gets included 20 times, each of these variables is duplicated 20 times". But there is header guard on constants.h. Does not preprocessor handle the situation in this case? Buy the way, this is a great tutorial. Thanks.

    • Alex

      Header guards prevent a header from being included more than once into the same file.

      in a.cpp:

      Header guards do not prevent a header from being included into multiple separate files.

      in a.cpp:

      in b.cpp:

      In this case, iostream will be copied into both a.cpp and b.cpp.

      Now instead of iostream, let's assume we're including a header file full of constants definitions.

      In the first example, a.cpp would only get one copy of those constants.
      In the second example, both a.cpp and b.cpp would get a separate copy of those constants.

  • Danny

    I'm no C++ pro, but from learning from your website, isn't this a mistake?

    "Note that if you want to define an uninitialized non-const global variable, do not use the extern keyword..."

    Shouldn't it be "...want to *declare* an uninitialized..."?
    Uninitialized mean it hasn't been defined, only declared. Am I wrong?

    Yes, I am a pedant, but we pedants have our own learning styles too.

    • Alex

      > Uninitialized mean it hasn’t been defined, only declared. Am I wrong?

      You are wrong. :)

      A declaration associates a name and type, but does not instantiate an object.
      A definition actually instantiates the object.

      The top line in the code block above is a definition of an uninitialized variable. Memory will be allocated for x, even though it hasn't been assigned a value yet.

      • Danny

        Ah, that helps. So is

        both a declaration and a definition? That's what this* guy says: "The line int x; both declares and defines the variable." If so, that was the source of my confusion.


        • Alex

          Yes, "int x" is both a definition and a declaration. All definitions in C++ are declarations, but only some declarations are definitions. Others, such as forward declarations, are pure declarations.

          I discuss exactly this in lesson 1.7 -- forward declarations.

  • Hi, In the example above, it is actually global value of 4 and local value of 8.

    BTW nice work...

    I'm following each word of this tutorial.


  • cpplearner

    When you state:

    "While this is simple (and fine for smaller programs), every time constants.h gets #included, each of these variables is copied into the including code file. If constants.h gets included 20 times, each of these variables is duplicated 20 times. That’s not too much of a problem here, but if this list of constants were large, and/or included memory-intensive variables, it could lead to code bloat."

    From what I remember from the previous lessons you said that using the preprocessor commands like #ifndef #define and #endif, even if you do include the file multiple times they will not be duplicated. What is the difference? Or am I completely missing some point here?

    • Alex

      I see I wasn't as clear as I could have been. Header guards are meant to prevent the same header file from being included multiple times into the same sound file.

      Header guards do not prevent the header file from being included once into multiple different files.

      In this case with the symbolic constants, it's the latter case that I'm talking about.

  • Jack

    Hey, I am a bit confused about the conversion of the constants.h into external constants to reduce bloating part, I include the constants.h file in the main program but what about constants.cpp, don't I need to include it also or how do I link it?

  • codeez

    It should be noted if your global variables are const and they are to be used externally, their original definitions also need the extern keyword. E.g.:

    // file1.cpp

    // illegal:
    const int x = 33;
    // correct:
    extern const int x = 33;

    // main.cpp
    extern const int x; // forward decleration

    Of course you can actually declare global consts without extern, but if they need external access use extern for both sides!

    • Alex

      Thanks for the tip. I've updated the lesson to include this information.

      Unfortunately, the fact that non-const and const global variables behave differently makes this section a little more complicated than it was before.

  • hpoonis

    I have to ask...

    Why would you need to create a file (say) globals.cpp AND ALSO globals.h to call the .cpp? Why not just call the file globals.h instead and use that?

    It just seems pointless having two files do the same thing as one.

  • Anuradha

    i am using a global variable 'int bsize' in multiple file using header file system..i am getting the following error...

    I have declared it in the file called test1.cpp as

    included it with extern keyword in the file test1.h as

    and then accessed it in two files keyboard.cpp and numpad.cpp as a part of formula

    please reply..why is that error? how should i resolve it?

    • qaz

      @Anuradha: "int bsize" was declared locally in the function sizeHint() in test1.cpp. It doesn't exist outside that function. Declare it globally in test1.cpp outside any functions.

  • ArnR

    Is there any difference between declaring global variable in C & C++?
    If yes then please explain with an example.

    Thanks for this nice tutorial guide.. :)

  • Alex B.

    Hi! I'm using Dev-C++, and I'm new to C++

    I copied and pasted the code(s) with the extern variable header.
    I got a compiling error that says that it cannot link them:

    [Link error] undefined refrence 'to g_nValue'
    [Link error] undefined refrence 'to g_nValue'
    Id returned 1 exit status

    What's going on... Please help :(

  • Kavya

    Can you tell me wht will happen if below is the case ??

    int gvalue = 5 ;
    int gvalue = gvalue ;
    print ("%d",gvalue);

    • Delaney

      when you use:

      it uses the local gvalue and returns
      local gvalue = -858993460

      if you wanted it to return 5 use the code:

  • Sam

    In C, I use globals when I need a pointer to the start (and/or end) of a linked list, which is referenced and modified by many functions. Is this wrong?

    In C++, what in essence should I be doing instead to keep track of something like this - the initial address of a linked list- throughout an entire program? I don't want to pass it around. Am I lazy?

    Thanks for these tutorials - I took out several books from the library to get some answers on use of header files, globals and extern in C++ and none were as helpful as this.

  • N.Kumaresh

    Thanks for this free, and hence great site.

  • Whiskeydash

    Fully mindful of the global warning (and their emissions),
    would "extern" also be used in the case of using a 'global function' if one was er declared (or is it defined..) externally?

    • Alex

      The extern keyword can be used with forward declaration for functions. However, unlike variables (which need the keyword extern to indicate that the declaration is a forward declaration), function forward declarations are assumed to be extern, so use of the extern keyword is optional (and redundant) with function prototypes.

  • Ian

    Well, what happens if I have two different files containing the same variable name, where one of them was intended to be global and the other local. How does the compiler know which variable I am referring to, when I write 'extern int identifier' above my int main() block. I guess Im asking this question coz Im used to MatLab7.0 , where i had to prefix "global" to a variable declaration, to denote it was global. This was stored in the workspace during runtime and accessed through there.

    • Generally a local variable will take precedence over a global. eg.

  • Elef8eroskopefths

    Thanks 4 all info, but may I ask sth??
    am writin' a prog the last 3 days and when I initialize a funktion I need some variables (a lot, to be honest :P), which I need in the main() function as well, but the user is the one who decides how many variables there will be every time he uses ('will use', when I finish it) the prog. So I cannot declare a function 4 example: 'func(x;y;z)' because I cannot know how many the variables will be, so I cannot see a way 2 pass data between functions without global variables....

    Is there sth I don't know, which I can use at such an example, in order not to use globals???? If yes, I NeEd It

  • noob1337

    Alex, you are my C++ Jesus. Thank you for spreading the almighty commandments of programming, I worship you for that.

    Actually I had a question but I just figured it out :) Maybe I'll have one for you later..

  • Vivek Singh

    Thanks that was great!

    I was facing problem with global variable declaration and using it into mutiple files.

    The problem is fixed.

    • papagym177

      The comments in the last program in Sect 4.2 has me confused again. Doesn't g_mode get changed back to one (1) in function Main by the next statement- {int g_mode = 1;... THEREFORE: global it's 1, dosomething it's 2, then in main it's 1 again??? Is one of the declarations hidden again?
      Sorry if I'm so picky ..Thank You.

      • CodeAvenger

        The Function doSomething is called within main. So first the variable g_mode is equal to 1, because of the global variable with that name. Then it is equal to 1, because when we go into main, there is a local variable, with the same name that is equal to 1. Then the doSomething Function is called and g_mode is equal to 2. We then go to the if statement that prints out "Launching nuclear missiles...".

        • Alex

          There is no local variable named g_mode. There is only a global variable named g_mode.

          When main sets g_mode to 1, it's somewhat redundant because g_mode was already set to 1 when it was initialized.

          Then doSomething() is called, which changes the value of g_mode to 2.

          When the if statement executes, (g_mode == 1) evaluates to false, so the else statement case is executed.

          And then the world ends.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]