【问题标题】:Compiling a C Source through javacode通过java代码编译C源代码
【发布时间】:2012-06-26 09:08:27
【问题描述】:

我正在尝试通过 javacode 编译 C 程序。我是这样做的。

    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 未创建并显示以下错误消息。 /usr/bin/sh: gcc: 找不到命令

【问题讨论】:

    标签: java c gcc gnu


    【解决方案1】:

    一个问题是exec(String) 在空白字符处天真地将字符串拆分为参数。您需要为它进行拆分。将exec 写为:

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

    exec(String) 方法不理解引用和重定向等 shell 语法。

    可能还需要为gcc 命令使用完整路径名,但我对此表示怀疑。 shell 应该从 JVM 继承环境变量设置,这可能包括一个合适的 PATH 变量。

    【讨论】:

    • 试过这个...这次没有出现错误信息。控制台上没有显示任何内容。也没有创建 HelloWorld.exe。
    • 尝试一些实验。 1) 尝试从 windows 命令提示符运行命令。 2) 将“gcc HelloWorld.c -o HelloWorld.exe”替换为“cat HelloWorld.c”或“ls -l HelloWorld.c”或“ls -ld”。
    【解决方案2】:

    您可以获取当前运行时环境并调用 exec 方法。这是一个例子:

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

    【讨论】:

    • 那无济于事。阅读 exec(String) 的 javadoc 以了解它如何将字符串拆分为参数。
    【解决方案3】:

    试试

    /usr/bin/gcc
    

    而不是

    gcc
    

    比如说,在脚本中使用二进制调用的完整路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多