首先,我有一个 singleton.cpp 文件来构建单例对象,并使用声明实例属性((构造函数))
#include<iostream>
using namespace std;
class singleton{
public:
singleton(){cout<<"singleton ctor\n";}
};
__attribute__((constructor)) static void beforeFunction()
{
printf("beforeFunction\n");
singleton obj;
}
和一个简单的main.cpp
#include<iostream>
using namespace std;
int main(){
return 0;
}
我一起构建 main.cpp singleton.cpp :
g++ singleton.cpp main.cpp -o main
./main
beforeFunction
Segmentation fault
那么为什么我的程序崩溃了,发生了什么?如何修复它?我在 ubuntu 上使用 gcc。多谢。
我复制了这个g++ (Debian 7.3.0-5)
,并且g++ (GCC) 9.0.0 20180902 (experimental)
.
有趣的是,这失败了:
$ g++ singleton.cpp main.cpp && ./a.out
beforeFunction
Segmentation fault
但这按预期工作:
$ g++ main.cpp singleton.cpp && ./a.out
beforeFunction
singleton ctor
正如橡子正确指出的那样,iostream
/ std::cout
当您调用单例构造函数时,机器尚未正确初始化。发生这种情况是因为有特殊代码发出到main.o
(and only main.o
) 调用std::ios_base::Init::Init()
。也只是因为main.cpp
有无关的#include <iostream>
.
如何修复它?
最好的解决方法是不使用__attribute__((constructor))
at all。就您而言,没有理由做您正在做的事情。改为这样做:
// singleton2.cpp
#include<iostream>
using namespace std;
class singleton{
public:
singleton(){cout<<"singleton ctor\n";}
};
static singleton obj;
使用上面的代码,任一链接顺序都有效:
$ g++ main.cpp singleton2.cpp && ./a.out
singleton ctor
$ g++ singleton2.cpp main.cpp && ./a.out
singleton ctor
如果你坚持使用__attribute__((constructor))
,然后确保main.o
在您的链接线上before任何其他可以使用的对象iostream
s.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)