Running C++ code outside of functions scope

One way of solving it is to have a class with a constructor that does things, then declare a dummy variable of that class. Like

struct Initializer
{
    Initializer()
    {
        // Do pre-main initialization here
    }
};

Initializer initializer;

You can of course have multiple such classes doing miscellaneous initialization. The order in each translation unit is specified to be top-down, but the order between translation units is not specified.


You don't need a fake class... you can initialize using a lambda

auto myMap = []{
    std::map<int, string> m;
    m["test"] = 222;
    return m;
}();

Or, if it's just plain data, initialize the map:

std::map<std::string, int> myMap { { "test", 222 } };