Compiling C code from a Java program

独自空忆成欢 提交于 2019-12-12 05:58:43

问题


I am trying the following code to compile an external C program with a Java program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public static void main(String[] args){
    try{
        Runtime rt=Runtime.getRuntime();
        Process pr=rt.exec("cmd /c PATH=%PATH%;c:\\TC\\BIN");
        pr=rt.exec("cmd /c c:\\TC\\BIN\\TCC.exe c:\\TC\\EXAMPLE.c");
        pr=rt.exec("c:\\TC\\EXAMPLE.exe");
        BufferedReader input=new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line=null;

        while((line=input.readLine())!=null){
            System.out.println(line);
        }
        int exitVal=pr.waitFor();
        System.out.println("exited with error code "+exitVal);
    }
    catch(Exception e){
        System.out.println(e.toString());
        //e.printStackTrace();
    }
}
}

but I am getting:

java.io.IOException: Cannot run program "c:\TC\EXAMPLE.exe": CreateProcess error=2, The system cannot find the file specified

The compilation process is not working, so what else can I do to compile my C code?


回答1:


Please use the Processbuilder API for this, The documentation has an example of how to use the various flags.




回答2:


I think that you are calling the compiled program before it had the chance to be generated. You should wait on the call:

pr=rt.exec("cmd /c c:\\TC\\BIN\\TCC.exe c:\\TC\\EXAMPLE.c");

To finish before you try calling the compiled output.



来源:https://stackoverflow.com/questions/12340922/compiling-c-code-from-a-java-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!