【发布时间】:2019-03-05 14:32:52
【问题描述】:
我正在编写一个小的共享库来通过 LD_PRELOAD 测试一些东西,我想将日志写入文件。
以下代码有效:
void ctor() __attribute__((constructor));
void dtor() __attribute__((destructor));
void ctor() {
std::ofstream log_file;
log_file.open("/home/tristan/Test.log");
log_file << "Log Stuff..." << std::endl;
log_file.close();
}
这会导致段错误:
void ctor() __attribute__((constructor));
void dtor() __attribute__((destructor));
std::ofstream log_file;
void ctor() {
log_file.open("/home/tristan/Test.log");
log_file << "Log Stuff..." << std::endl;
log_file.close();
}
这是为什么呢?可能与构造函数属性有关?
我的 GCC 标志如下:
gcc -fPIC -m64 -shared -lstdc++ -o Test.so *.cpp
【问题讨论】:
-
log_file不应该属于函数ctor有什么原因吗? -
我计划在全球范围内使用 log_file。在 ctor 中打开它,在我的其他函数中输出,然后在 dtor 中关闭它。
标签: c++ linux fstream ofstream