直接在ProcessBuilder中使用gcc不会创建输出文件

时间:2018-03-13 09:12:10

标签: java gcc compilation

我正在尝试使用gcc使用ProcessBuilder编译C源文件。我设法让它运行但没有输出文件。

这是我的代码(基于this answer):

public void compileWithGccNoCmd(Path sourcePath) throws IOException {
        String sourcePathString = sourcePath.toString();
        String outputPathString = sourcePath.getParent().toString() + "\\" + Files.getNameWithoutExtension(sourcePath.toString());

        try {
            ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs -ftest-coverage -o " + outputPathString,  sourcePathString);
            pb.directory(sourcePath.getParent().toFile()); // this was added later
            Process compile = pb.start();

            compile.waitFor();

            if (compile.exitValue() == -1) {
                // if error
                System.out.print("COMPILE ERROR");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

}

我首先想到它与工作目录有关,所以我添加了pb.directory()但输出文件仍然没有。

由于我找不到任何解决方案,因此我尝试使用gcc cmd运行public void compileWithGcc(Path sourcePath) throws IOException { String sourcePathString = sourcePath.toString(); String outputPathString = sourcePath.getParent().toString() + "\\" + Files.getNameWithoutExtension(sourcePath.toString()); ProcessBuilder pb; try { pb = new ProcessBuilder("cmd", "/C", "gcc " + sourcePathString + " -o " + outputPathString + " -fprofile-arcs -ftest-coverage"); pb.directory(sourcePath.getParent().toFile()); Process p = pb.start(); p.waitFor(); int x = p.exitValue(); } catch (Exception ex) { ex.printStackTrace(); } } 。我设置工作目录以确保输出文件在正确的位置。这是替代代码(基于this answer):

gcc

出于某种原因,它有效!为什么会这样?我很确定两个都使用相同的参数

运行public search2(): Observable<string[]> { return Observable.of( { "aa","dd", "cc" } ); }

1 个答案:

答案 0 :(得分:1)

这一行:

ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs -ftest-coverage -o " + outputPathString,  sourcePathString)

需要看起来像这样:

ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs", "-ftest-coverage", "-o", outputPathString,  sourcePathString)

你在第一行做的是将两个参数传递给gcc,其中一个是"-fprofile-arcs -ftest-coverage -o " + outputPathString,而不是传递我编辑的行的五个参数。 gcc不会理解这一点。

当您像使用cmd一样使用cmd时,它会解析您提供的命令并正确传递参数,这就是它的工作原理。