用Java编译和运行C程序

我试图从这个链接运行源代码

从Java应用程序编译并运行源代码

我安装了Mingw32编译器更改了编译器位置路径,并在Eclipse中运行示例.cpp文件时出现此错误。

public class C_Compile { public static void main(String args[]){ String ret = compile(); System.out.println(ret); } public static String compile() { String log=""; try { String s= null; //change this string to your compilers location Process p = Runtime.getRuntime().exec("cmd /C \"C:\\MinGW\\bin\\mingw32-gcc-4.6.2.exe\" C:\\MinGW\\bin\\Hello.cpp "); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); boolean error=false; log+="\n....\n"; while ((s = stdError.readLine()) != null) { log+=s; error=true; log+="\n"; } if(error==false) log+="Compilation successful !!!"; } catch (IOException e) { e.printStackTrace(); } return log; } public int runProgram() { int ret = -1; try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("cmd.exe /c start a.exe"); proc.waitFor(); ret = proc.exitValue(); } catch (Throwable t) { t.printStackTrace(); return ret; } return ret; }} 

错误:

 mingw32-gcc-4.6.2.exe: error: CreateProcess: No such file or directory 

谁能告诉我在哪里放置我的Source .cpp文件。 谢谢

错误消息表明找不到gcc编译器本身。 你为什么不使用gcc.exe而不是mingw32-gcc-4.6.2.exe呢? 如果您更新MinGW,后者将无效! 此外,当路径不包含空格字符时,您不需要在字符串中使用\“。

您可以将cpp文件放在任何您想要的位置,提供该gcc的路径。 Exec还应该有一个参数dir ,你可以设置为你的cpp目录。

  public static void CompileCprog(String filename){ File dir = new File("C://Users//JohnDoe//workspace//Project"); try { String exeName = filename.substring(0, filename.length() - 2); Process p = Runtime.getRuntime().exec("cmd /C gcc " + filename + " -o " + exeName, null, dir); // Process p = Runtime.getRuntime().exec("cmd /C dir", null, dir); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } 

这对我来说很完美。

“dir”变量可以设置为您想要的任何位置。

第一个“p”进程编译一个程序,并在您正在编译的程序的同一位置生成一个具有相同名称(减去.c)的.exe文件。

如果您的命令有输出,则可以使用缓冲的阅读器。 如果您将命令字符串更改为.exec(“cmd / C dir”); 结果将打印在输出中。 (即时通讯使用eclipse)