Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling a C Source through javacode

Tags:

java

c

gcc

gnu

I am trying to compile a C program through a javacode. I did it as follows.

    Process process = Runtime.getRuntime().exec("C:/cygwin/bin/sh -c 'gcc HelloWorld.c -o HelloWorld.exe'");

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line, log;
    log ="\n..Input..\n";
    while ((line = br.readLine()) != null) {
      log+=line;
      log+="\n";
    }

    InputStream is2 = process.getErrorStream();
    InputStreamReader isr2 = new InputStreamReader(is2);
    BufferedReader br2 = new BufferedReader(isr2);
    String line2;
    log+="\n..Error..\n";
    while ((line2 = br2.readLine()) != null) {
      log+=line2;
      log+="\n";
    }
    System.out.println(log);

HelloWorld.exe is not created and following error message was displayed. /usr/bin/sh: gcc: command not found

like image 742
Taani Avatar asked Mar 27 '26 01:03

Taani


1 Answers

One problem is that exec(String) splits the string into arguments naively at the white-space characters. You need to do the splitting for it. write the exec as:

Process process = Runtime.getRuntime().exec(new String[]{
     "C:/cygwin/bin/sh",
      "-c",
      "gcc HelloWorld.c -o HelloWorld.exe"});

The exec(String) method does not understand shell syntax such as quoting and redirection.

It might also be necessary to use a full pathname for the gcc command, but I doubt it. The shell should inherit the environment variable settings from the JVM, and that probably includes a suitable PATH variable.

like image 135
Stephen C Avatar answered Mar 28 '26 14:03

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!