In a project I am doing I use some global variables using "extern" so that all files can access them.
The following is my case:
main.cpp:
#include <iostream>
#include "test.h"
std::string val2 = val;
int main()
{
std::cout << val2 << std::endl;
}
test.h:
#pragma once
#include <string>
extern std::string val;
test.cpp:
#include "test.h"
std::string val = "Hello World";
And what I am expecting to get as output is "Hello World" however it will just print a new line.
If instead of std::string I use a built-in type (like int) it will work as expected.
From my understanding, what happens is val
has not been initialized when we are trying to assign it to val2
, so we end up copying nothing, then after that (probably) val
gets initialized with the value Hello World
but since we are printing val2
we get only the new line.
So my question is, How can I force val
to initialize first.
If that's not possible, how can I make global variables (that can be used between multiple files)
NOTE: Those are not my real files but I checked and the problem appears here as well, I think this counts as a Minimal Code Example (or whatever it is called)