我正在使用一些静态库建立我的程序(测试)。 这个库包含一个文件,其中有我的功能:
I'm building my program (tests actually) using some static library. This library contains one file inside which I have functions like that:
string& GetString() { static string strFilename; return strFilename; } void PrintToScreen() { printf("String: %s\n", GetString().c_str()) }然后在我的main.cpp(库外)中:
Then in my main.cpp (outside the library) I'm doing:
GetString() = "abc"; printf("String: %s\n", GetString().c_str()); PrintToScreen();我得到这个输出:
String: abc String:第二次调用函数(但是从不同的文件,这是在库内部)某种方式清除以前的值,重新初始化它,或使用它的自己的副本。 I改变GetString函数使用'new',但结果是完全一样的(btw。程序从不崩溃)。 但是我不明白热的可能吗? 任何想法我错了什么?
So looks like second call to the function (but done from different file, which is inside the library) somehow clear previous value, reinitialize it, or uses own copy of it. I changed GetString function to use 'new' but result is exactly the same (btw. program never crash). But I don't understand hot it's possible? Any ideas what I'm doing wrong?
-------------------- ----------- UPDATE ------------------------------则
------------------------------- UPDATE ------------------------------
0000000000000030 T _Z16GetLogprintfFilevogle 0000000000000008 b _ZGVZ16GetLogprintfFilevE16strLogprintfFileogle 0000000000000018 b_ZZ16GetLogprintfFilevE16strLogprintfFileã U _Z16GetLogprintfFilev
并在我的基础库上使用nm(由最终lib使用)我得到:
and with nm on my base lib (used by final lib) I get:
0000000000000030 T _Z16GetLogprintfFilevogle 0000000000000008 b_ZGVZ16GetLogprintfFilevE16strLogprintfFileã 0000000000000018 b_ZZ16GetLogprintfFilevE16strLogprintfFileã
推荐答案实例中有一个缺少想法。它应该看起来像这样:
Actually there was one missing think in example. It should look like this:
string& GetString() { static string strFilename; return strFilename; } extern "C" { void PrintToScreen() { printf("String: %s\n", GetString().c_str()) } }奇怪。无论如何,我重构了这样的东西:
Strange. Anyway, I refactored it to something like this:
extern "C" { string* GetString() { static string strFilename; return &strFilename; } void PrintToScreen() { printf("String: %s\n", GetString()->c_str()) } }现在它没有问题。 对我来说,编译器并不抱怨,似乎很奇怪。 感谢他们的贡献,问题现在解决了。
And it works without problem now. Still it seems strange to me that compiler was not complaining. Thanks to all for their contribution, problem is solved now.
--------------- -------------------编辑------------------------------
---------------------------------- EDIT ----------------------------------
我以后再次遇到这个问题,所以它不是正确的修正。\\ 真正的问题是一些singleton被初始化 在类构造函数中:
I experienced this problem again later so it was not proper fix. The real problem was some singleton which was initialized in meantime and had in the class constructor:
GetString() = "";所以,简单的问题,但很难跟踪...
So, simple problem, but really hard to track...
更多推荐
可以“首次使用时构建”成语在任何情况下都会失败?
发布评论