Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are global variables created?

I have a piece of code structured like this:

a.cpp:  
    #include "b.hpp"  
    const unsigned a =  create(1);


b.cpp:
    map<int, string> something; // global variable
    unsigned create(unsigned a){
        something.insert(make_pair(a, "somestring"));
        return a;
    }

Now, this throws out a segfault, valgrind says that map was not yet created. How does it work, how should I change it?

like image 456
darenn Avatar asked Oct 27 '13 13:10

darenn


People also ask

Where global variables are created?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

When Should a variable be global?

A global variable is defined outside all functions and it accessible to all functions in its scope. A global variable can be accessed by all functions that are defined after the global variable is defined.

How global variables are declared?

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It's usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.

Are global variables automatically initialized to 0?

Yes, all members of a are guaranteed to be initialised to 0. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.


1 Answers

C++ does not define an order for when global variables are constructed during program startup. a could be initialized first before something gets constructed which would cause the problem above. When you start constructing global variables that depend on other global variables being initialized then you run into the classical static initialization order fiasco.

An easy way to fix your above scenario is to make something static and move it into your create function.

unsigned create(unsigned a)
{
    static map<int, string> something;
    something.insert(make_pair(a, "somestring"));
    return a;
}

That will guarantee something gets created on first call to create.

like image 154
greatwolf Avatar answered Oct 14 '22 06:10

greatwolf