c++ - 如何将 llvm::outs() 重定向到文件?

标签 c++ stream llvm nm

我正在使用一些 LLVM 工具(如 llvm-nm)作为静态库。 IE。我复制了源代码 llvm-nm.cpp,将 main(..) 重命名为 llvm_nm(..) 并将其编译为静态库。我想将标准输出转发到我的文件。

我尝试使用下一种方法:

  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:

完成的
outs() << "Archive map" << "\n";

it's implemented下一个方法:

/// 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 }

如何将该输出重定向到我的文件?

最佳答案

我意识到这是一个老问题,但是,我在查找 llvm 的 outs() 流的一些简单信息时遇到了这个问题,我发现了 here .

llvm“BrainF”附带的示例之一是这样使用它的:

  ...

  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;

  ...

所以这似乎表明您可以安全地重定向。

注意:在此示例中,OutputFilename/InputFilename 是使用 llvm 的支持库创建的 std::string 类型 CommandLine .

关于c++ - 如何将 llvm::outs() 重定向到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317177/

相关文章:

C++,协作 FILE* 和 std 流

c# - 我可以使用流解压缩和反序列化文件吗?

c++ - 在 Clang 中对字符串进行 pretty-print 语句

c++ - 通过小部件获取顶级窗口

c# - 能否返回 CryptoStream 并仍然正确处理所有内容?

c++ - boost库中的矩阵赋值如何与括号一起使用?

types - LLVM 任意精度整数

c++ - 在 C++ 11 中使用 Homebrew 软件、gcc 和 llvm

c++ - Maven NAR 插件 : DLL dependency not found on path

C++/Windows 多线程同步/数据共享