0

I have a global variable initialized as such:

main.cpp

map<const string, vector<string>> cmdOutputMap({ {cmd1, output1},
                                                 {cmd2, output2},
                                                 {cmd3, output3} });

commands.h

extern const std::string cmd1;
extern const std::string cmd2;
extern const std::string cmd3;

commands.cpp

std::string cmd1 = "-text1";
std::string cmd2 = "-text2";
std::string cmd3 = "-text3";

It compiles fine, however, in debug, cmdOutputMap has a size of 1, with the only key being "".

If, instead of using the variables cmd1, cmd2, cmd3, I use their values (see below), then cmdOutputMap has a size of 3, with the right keys populated.

map<const string, vector<string>> cmdOutputMap({ {"-text1", output1},
                                                 {"-text2", output2},
                                                 {"-text3", output3} });

Is it wrong to initialize a std::map with variables?

Thanks,

Fred

fchasse
  • 11
  • 2
  • 1
    Please edit your question to contain [mcve]. Note you do not need to make key `const`, `std::map` will do that for you – Slava Jan 09 '20 at 16:11
  • 5
    No, but using global variables defined in different modules like that results in undefined behavior because you don't know which global gets initialized first. There's a dup for that somewhere. – 1201ProgramAlarm Jan 09 '20 at 16:12
  • 1
    "Is it wrong to initialize a std::map with variables?" it is wrong to initialize one global variable with another from different compilation unit, if that global a `std::map` instance or not is irrelevant – Slava Jan 09 '20 at 16:18
  • [This answer](https://stackoverflow.com/a/3746249/5231607) explains some of the rules governing global variable initialization. – 1201ProgramAlarm Jan 09 '20 at 16:24
  • It seems to be an "initialization order fiasco" problem. I will use a function to initialize the variable. – fchasse Jan 09 '20 at 16:37

0 Answers0