c++ cmake 动态库的 std::string 为空,求指点(maocs-12.6)

查看 170|回复 13
作者:wjx0912   
代码和截图: https://github.com/wjx0912/cmake_macos_cpptest
https://github.com/wjx0912/cmake_macos_cpptest/raw/main/screenshot.png
万分感谢

std, cmake, string, maocs

wjx0912
OP
  
猜测的原因:__attribute__((constructor))时,c++ runtime 还未初始化,std::string 的一些操作可能不稳定。
测试:
```
std::string g_test1;
std::string g_test2;
__attribute__((constructor))
static void init() {
g_test1 = "hello test1";
printf("init: %s\n", g_test1.c_str());
}
void hello_func1(void) {
g_test2 = "hello test2";
printf("Hello World: %s, %s\n", g_test1.c_str(), g_test2.c_str());
return;
}
void hello_func2(void) {
printf("Hello World: %s, %s\n", g_test1.c_str(), g_test2.c_str());
return;
}
```
在 hello_func2 里面,g_test1 无法打印,g_test2 正常。
不知道这个思路是否正确,求大神指点
chingyat   
应该是 init() 在 g_test 初始化之前就被调用了。
wjx0912
OP
  
```
搞定了,把:
std::string g_test1;
std::string g_test2;
改成:
__attribute__((init_priority(101))) std::string g_test1;
__attribute__((init_priority(101))) std::string g_test2;
参考:
https://stackoverflow.com/questions/43941159/global-static-variables-initialization-issue-with-attribute-constructor-i
```
chingyat   
```c++
#include
#include
#include
#include
#include "hello.h"
std::string g_test = "initial value";
__attribute__((constructor))
static void init()
{
g_test = "hello test";
printf("init: %s\n", g_test.c_str());
}
void hello_func(void) {
printf("Hello World: %s\n", g_test.c_str());
return;
}
```
执行结果:
```
init: hello test
Hello World: initial value
```
wjx0912
OP
  
这个不是编译器 bug ,是未指定行为
Shatyuka   
`__attribute__((constructor))`在全局变量初始化之前执行。试试给全局变量添加`__attribute__((init_priority(101)))`属性。
wjx0912
OP
  
@chingyat 嗯。这个是没问题的。但是 g_test 不是固定值(会从文本读取)。runtime 执行一堆 constructor 的顺序问题。
wjx0912
OP
  
@Shatyuka 正解。谢谢
wjx0912
OP
  
@Shatyuka windows 的 DllMain.DLL_PROCESS_ATTACH 执行的比较晚,所以不会有这个问题,对吧
您需要登录后才可以回帖 登录 | 立即注册

返回顶部