如何在eclipse中的java程序中编译C ar C ++代码并进行错误记录?

时间:2013-03-03 07:19:52

标签: java eclipse compiler-errors mingw

我必须在java中开发一个程序,它以C或C ++文件作为输入并编译文件并给出程序中发现的错误的位置,位置和类型。我更关注语法错误。我需要一种在eclipse java中执行此操作的方法。我已经安装了Eclipse CDT插件,我不知道是否可以从java程序中调用编译器并获取行号,位置和位置。

我已经尝试安装编译器,即MinGW编译器,并且能够打印错误,但我没有按照我想要的方式得到错误。 这是我尝试a link

的链接

有人可以帮助我捕获阵列中C程序中发现的语法错误的行号吗?

1 个答案:

答案 0 :(得分:1)

您必须解析stdoutstderr的结果。在您链接的问题中,您可以找到如何访问它们的解决方案。

您还提到过您希望拥有编译器错误的监听器。

public interface CompilerErrorListener {
    public void onSyntaxError(String filename, String functionName, 
        int lineNumber, int position, String message);

    public void invalidOutputLine(String line);
}

您可以通过任何实现实现此目的:

public class CompilerErrorProcessor implements CompilerErrorListener {
    public void onSyntaxError(String filename, String functionName, 
        int lineNumber, int position, String message) {
        ....
        // your code here to process the errors, e.g. put them into an ArrayList
    }

    public void invalidOutputLine(String line) {
        // your error handling here
    }
}

那么,让我们解析编译器输出! (注意,这取决于您的编译器输出,并且您只提供了2行输出)

BufferedReader stdError = ...
String line;

CompilerErrorListener listener = new CompilerErrorProcessor(...);

String fileName = "";
String functionName = "";
int lineNumber = -1;
int position = -1;
String message = null;

while ((line = stdError.readLine()) != null) {
    // the line always starts with "filename.c:"
    String[] a1 = line.split(":", 2);
    if (a1.length == 2) {
        // a1[0] is the filename, a1[1] is the rest
        if (! a1[0].equals(fileName)) {
            // on new file
            fileName = a1[0];
            functionName = "";
        }
        // here is the compiler message
        String msg = a1[1];
        if (msg.startsWith("In ")) {
            // "In function 'main':" - we cut the text between '-s
            String[] a2 = msg.split("'");
            if (a2.length == 3) {
                functionName = a2[1];
            } else {
                listener.invalidOutputLine(line);
            }
        } else {
            // "9:1: error: expected ';' before '}' token"
            String[] a2 = msg.split(":", 3);
            if (a2.length == 3) {
                lineNumber = Integer.parseInt(a2[0]);
                position = Integer.parseInt(a2[1]);
                message = a2[2];

                // Notify the listener about the error:
                listener.onSyntaxError(filename, functionName, lineNumber, position, message);
            } else {
                listener.invalidOutputLine(line);
            }
        }

    } else {
        listener.invalidOutputLine(line);
    }

}

这不是一个完整的例子,当然,可能有更多的可能性,但希望你有这个想法。不要忘记记录无效/未处理的分支。

由于您使用特定的编译器,因此必须适应其输出。此外,编译器版本的更改可能会导致解析代码的更改。需要特别注意发现输出的结构,当你想要解析它时它会付出代价。