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 )

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.