如何将llvm :: outs()重定向到文件? [英] How to redirect llvm::outs() to file?
问题描述
我正在使用一些LLVM工具(例如 llvm-nm
)作为静态库.IE.我复制了源llvm-nm.cpp,将 main(..)
重命名为 llvm_nm(..)
,并将其编译为静态库.我想将标准输出转发到我的文件.
I'm using some LLVM tools (like llvm-nm
) as static libraries. I.e. i copied source llvm-nm.cpp, renamed main(..)
to llvm_nm(..)
and compiled it as static library. I'd like to forward standard output to my file.
我尝试使用下一种方法:
I've tried to use the next approach:
int out_fd, err_fd;
fpos_t out_pos, err_pos;
// redirect out
fflush(stdout);
fgetpos(stdout, &out_pos);
out_fd = dup(fileno(stdout));
freopen(outFilename, "w", stdout);
// execute
int ret = llvm_nm(argc_, argv_);
// restore output
fflush(stdout);
dup2(out_fd, fileno(stdout));
close(out_fd);
clearerr(stdout);
fsetpos(stdout, &out_pos);
问题是它没有被转发(如果我在nm源代码中添加 printf()
而不是 nm
输出,则可以正常工作).我已经看过源了,我可以看到使用 llvm :: outs()
stream:
The problem is that it's not forwarded (it works if i add printf()
in nm source code but not for nm
output). I've looke to the source and i can see output is done using llvm::outs()
stream:
outs() << "Archive map" << "\n";
并且已实现的另一种方式:
/// outs() - This returns a reference to a raw_ostream for standard output.
00702 /// Use it like: outs() << "foo" << "bar";
00703 raw_ostream &llvm::outs() {
00704 // Set buffer settings to model stdout behavior.
00705 // Delete the file descriptor when the program exits, forcing error
00706 // detection. If you don't want this behavior, don't use outs().
00707 static raw_fd_ostream S(STDOUT_FILENO, true);
00708 return S;
00709 }
如何将输出重定向到我的文件?
How can i redirect that output to my file?
推荐答案
我意识到这是一个老问题,但是,我偶然发现它为llvm的outs()流查找了一些简单的信息,而我发现这里.
I realize this is an old question, however, I came across it looking up some simple information for llvm's outs() stream which I found here.
llvm"BrainF"随附的示例之一使用它的方式是这样的:
One of the examples that comes with llvm "BrainF" uses it like this:
...
raw_ostream *out = &outs();
if (!JIT) {
if (OutputFilename == "") {
std::string base = InputFilename;
if (InputFilename == "-") { base = "a"; }
// Use default filename.
OutputFilename = base+".bc";
}
if (OutputFilename != "-") {
std::error_code EC;
out = new raw_fd_ostream(OutputFilename, EC, sys::fs::F_None);
}
}
...
if (out != &outs())
delete out;
...
所以这似乎表明您可以安全地重定向.
So it seems to suggest that you are safe to redirect.
注意:在本示例中,OutputFilename/InputFilename是使用llvm的支持库 查看全文