4

My problem regards to compiling c++ file within java. I have tried execution of c#, it is fine. This extract code for compiling c#

ProcessBuilder launcher = new ProcessBuilder("gmcs","HelloWorld.cs");`

However, my code for c++

ProcessBuilder launcher =new ProcessBuilder("g++", "HelloWorld.cpp -o HelloWorld");

returns error=2, No such file or directory To indicate path I used
launcher.directory(new File(path)) in both of cases

4
  • Is this a C++ library that you're using? Commented Jan 30, 2013 at 14:53
  • print out that path somewhere in your code and see where it is. Commented Jan 30, 2013 at 14:55
  • 1
    The 1st thing I would think to check is whether g++ is in your PATH so that it can be called from wherever this java program is, and also whether the HelloWorld.cpp is in the same directory as your java app. Next I would check that I am using ProcessBuilder properly. Commented Jan 30, 2013 at 14:56
  • @TonyTheLion No, it is java library Commented Jan 30, 2013 at 15:05

1 Answer 1

7

You need to provide arguments separately:

ProcessBuilder launcher =
    new ProcessBuilder("g++", "HelloWorld.cpp", "-o", "HelloWorld");

Otherwise the whole argument string is passed as one argument to the g++ executable, and g++ tries to find a file named HelloWorld.cpp\ -o\ HelloWorld (using escaped spaces as you would on a Linux terminal).

See the documentation for details on the usage.

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

2 Comments

That solved me the compilation problem and created HelloWorld file. Then I am using launcher.command("g++","./HelloWorld") to run it, but this return me null. is it right use of method? or there are should be another way?
@Aidos That’s now how you run executables. Why are you trying to pass it to the compiler (g++) again? Just run it directly, that’ll work.

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.