I am building my program (tests actually) using some static library.
This library contains one file inside which I have functions like this:
string& GetString() { static string strFilename; return strFilename; } void PrintToScreen() { printf("String: %s\n", GetString().c_str()) }
Then in my main.cpp (outside the library) I do:
GetString() = "abc"; printf("String: %s\n", GetString().c_str()); PrintToScreen();
And I get this output:
String: abc String:
It looks like the second function call (but is made from another file that is inside the library) somehow clear the previous value, reinitialize it or use your own copy.
I changed the GetString function to use "new", but the result is exactly the same (by the way, the program never crashes).
But I do not understand how possible this is?
Any ideas what I'm doing wrong?
------------------------------- UPDATE --------------- --- ------------
- Testing is performed in a single-threaded environment.
- It works on some platforms, and on some it does not work (works with windows, MacOS and AIX, does not work on Linux, HP_UX, Solaris, FreeBSD ...)
- I checked the strFilename address at runtime (printf inside GetString) and looks like one variable without duplicates (the address is always the same)
- BUT, with nm in the last lib, I get something like this:
<i> 0000000000000030 T _Z16GetLogprintfFilev
0000000000000008 b _ZGVZ16GetLogprintfFilevE16strLogprintfFile
0000000000000018 b_ZZ16GetLogprintfFilevE16strLogprintfFile
U_Z16GetLogprintfFilev
and with nm on my lib base (using the final lib) I get:
<i> 0000000000000030 T _Z16GetLogprintfFilev
0000000000000008 b _ZGVZ16GetLogprintfFilevE16strLogprintfFile
0000000000000018 b_ZZ16GetLogprintfFilevE16strLogprintfFile
source share