2

I have a project for which I need to compile C programs. The project is in Java. I have to take the program into a JTextArea,(I am using Swing for GUI) , run it against a testfile and output the results into another JTextArea. But something seems to be wrong in my code.

Process p = new ProcessBuilder("c:\\MinGW\\bin\\cc.exe", "program.c").start();

program.c contains the program that user enter into TextArea, and "c:\MinGW\bin\cc.exe" is my c compiler. I checked that this is not raising any exception. It should create a file named a.exe in my current directory having program.c file, but it is not.What is the proper way to do it?

I saw two other post similar to this, but they also don't provide a simple clean solution for this. Also, I have to run the created executable file after it.

Thanks in advance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
l0k3ndr
  • 536
  • 5
  • 24
  • `ProcessBuilder` won't raise an exception if something goes wrong within the process (ie, the compiler fails), you should be reading the output of the process to be sure that nothing has gone wrong... – MadProgrammer Oct 28 '13 at 05:38
  • 2
    Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and (continue to) build the `Process` using a `ProcessBuilder`. *"I saw two other post similar to this.."* Links? – Andrew Thompson Oct 28 '13 at 05:40
  • @AndrewThompson Those links I forgot. They were coming in suggestions when I was giving title to this post.I will work on this tonight. – l0k3ndr Oct 29 '13 at 05:04
  • http://stackoverflow.com/questions/12340922/compiling-c-code-from-a-java-program?rq=1 one was this @AndrewThompson This is my first time at any forum and also I am newbie to java. – l0k3ndr Oct 29 '13 at 05:13

1 Answers1

2

What is the proper way to do it?

One way is to use javax.tools.JavaCompiler "to invoke Java™ programming language compilers from programs." There's an example here.

Community
  • 1
  • 1
Catalina Island
  • 7,027
  • 2
  • 23
  • 42