How to create a global variable

cpp Portugal
  • 14 years ago

    Hi:

    I need really need help, I can not figure how to create a global variable that can be changed and used in
    several classes.

    I got many suggestions, but i can not make any of them work, always get errors...

    the last solution i tried was doing a "afile.h" where i put the variable using extern... but then i got "linking" errors...

    How can i solve this problem? I just need a boolean variable that can be "seen" anywhere...

    Please help me, if possible write down the code, because each word I write today as at least one error...

    Thank you in advance














  • 14 years ago


    Put The Variable in a .cpp File.

    e.g.

    in File4.cpp

    int gVariable=0;



    Then Create a Header File Containing the prototype
    e.g.
    In File4.h


    #ifndef _GLOBALVAR
    #define _GLOBALVAR

    // NOTE: This is NOT an actual variable,
    // it just helps the Linker Find the real variable in the cpp file.
    extern int gVariable;

    #endif



    Now, add #include"File4.h" to the top of Every .cpp File that Needs to access the global Variable.






















Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth