1

I'm writing a Ruby code which generates a string containing a C++ program. For instance the Ruby string may contain:

#include <iostream>
using namespace std;int main(){cout<<"Hello World"<<endl;return 0;}

In order to run the C++ program stored in the Ruby string, I write the string into a file named c_prog.cpp, then use:

%x( g++ c_prog.cpp -o output )

to compile the C++ program in the file, then use:

value = %x( ./output )

and then print the value.

Since the C++ program stored in the Ruby string is very long (thousands of LOC), writing it to the file wastes some time. Is there any way I can compile the program stored in the string without writing it into a file? I mean something like:

%x( g++ 'the ruby string' -o output )

instead of:

%x( g++ c_prog.cpp -o output )
Mehran
  • 60
  • 7

2 Answers2

3

You can pass in a single dash as a file name to tell g++ to read from STDIN. So,

%x( echo 'the ruby string' | g++ -o output -x c++ - )

should do the trick. See this related question.

Community
  • 1
  • 1
Max
  • 15,157
  • 17
  • 82
  • 127
2

You can use the PTY library to pipe directly in to the g++ process:

require 'pty'

m, s = PTY.open
r, w = IO.pipe
pid = spawn("g++ -o output -x c++ -", :in=>r, :out=>s)
r.close
s.close
w.puts "#include <iostream>\n int main(){std::cout << \"Hello World\" << std::endl;}"
w.close
TartanLlama
  • 63,752
  • 13
  • 157
  • 193