gpt4 book ai didi

c++ - 如果在多个共享库中调用并且启用了libstdc++静态链接,则C++流变得很糟糕

转载 作者:行者123 更新时间:2023-12-01 14:57:04 58 4
gpt4 key购买 nike

我启用了--static-libstdc++编译了2个共享库。
2个共享库具有相同的函数f,它仅向stdout输出一个字符串和一个整数。
主程序将使用dlopen加载两个共享库,并使用f在其中调用dlsym
但是,第二个加载的共享库无法输出整数,并且C++流cout变为bad & fail

ADD: After discussion, I know this is normal... However, I want to change my question to: what implementation of libstdc++ caused this issue? Is there any shared global state? I think if there is no shared global state, it shouldn't be a problem. I wrote the similar program in Windows by static linking to VCRuntime and using LoadLibrary, and it works normally. So why libstdc++ is designed like this?



以下是2个共享库的代码。 (他们共享相同的代码)
他们只是 cout一个字符串和一个整数。
// dll.cpp

#include <iostream>

using namespace std;

extern "C" void f()
{
cout << "hi" << 1 << endl;

bool is_eof = cout.eof();
bool is_fail = cout.fail();
bool is_bad = cout.bad();

cout.clear();

cout << endl;
cout << "eof: " << to_string(is_eof) << endl;
cout << "fail: " << to_string(is_fail) << endl;
cout << "bad: " << to_string(is_bad) << endl;
}
这是主程序,它加载共享库并调用它们的 f函数。
// main.cpp

#include <iostream>
#include <dlfcn.h>
#include <cassert>

using namespace std;

using fn_t = void(void);

void call_f_in_dll(const char *dll_path)
{
auto dll = dlopen(dll_path, RTLD_LAZY);
assert(dll);
fn_t *fn = (fn_t *)dlsym(dll, "f");
assert(fn);
fn();
dlclose(dll);
}

int main()
{
call_f_in_dll("./libmydll.so");

cout << endl;

call_f_in_dll("./libmydll2.so");

return 0;
}
这是CMakeLists。
# CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project (TestGCC)

add_link_options(-static-libgcc -static-libstdc++)

add_library(mydll SHARED dll.cpp)
add_library(mydll2 SHARED dll.cpp)

add_executable (main main.cpp)
target_link_libraries(main dl)
输出为:
hox@HOX-PC:~/repos/test-gcc/out$ ./main
hi1

eof: 0
fail: 0
bad: 0

hi
eof: 0
fail: 1
bad: 1

Notice the second part, there is no 1 after hi and fail & bad become 1.


result
您可以在此处 checkout 代码: https://github.com/xuhongxu96/dlopen-iostream-issue

最佳答案

最后,我找到了一种解决Linux(GNU扩展)问题的方法。
使用dlmopen可以提供更好的隔离btw对象。

auto dll = dlmopen(LM_ID_NEWLM, dll_path, RTLD_LAZY);
非常感谢所有评论者!

Still welcome to explain the details about what the conflict states are.

关于c++ - 如果在多个共享库中调用并且启用了libstdc++静态链接,则C++流变得很糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63666660/

58 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com