编译循环依赖是如何工作的? [英] How does compiling circular dependencies work?
问题描述
我已经用 Java 制作了示例,但我认为(未经测试)它适用于其他(所有?)语言.
I've made the example in Java but I think (not tested) that it works in other (all?) languages.
您有 2 个文件.一、M.java
:
You have 2 files. First, M.java
:
public class MType {
XType x;
MType() {x = null;}
}
二、另一个文件(同目录),XType.java
:
Second, another file (in the same directory), XType.java
:
public class XType {
MType m;
public XType(MType m) {this.m = m;}
}
好吧,这是一个糟糕的编程,但如果你运行 javac XType
它会编译:甚至编译 MType
因为 XType
需要它.但是 ... MType
需要 XType
... 它是如何工作的?编译器如何知道发生了什么?
Ok it's bad programming, but if you run javac XType
it compiles: compiles even MType
because XType
needs it. But ... MType
needs XType
... how does that work? How does the compiler know what is happening?
我想知道编译器(javac 或您知道的任何其他编译器)如何管理这种情况,而不是如何避免这种情况.
I would like to know how the compiler (javac or any other compilers you know) manages that situation, not how to avoid it.
我问这个问题是因为我正在编写一个预编译器并且我想处理这种情况.
I'm asking because I'm writing a precompiler and I would like to manage that situation.
推荐答案
你需要通过 2-pass,或者 multi-pass 方法:
You need to take a 2-pass, or multi-pass approach:
像 Java 这样的语言需要一个多遍编译器,因为 x 的定义不需要在使用之前出现:
Languages like Java require a multi-pass compiler since the definition of x would not be required to come before the use:
public class Example {
public static void main(String [] args) {
assert(x==0);
x++;
assert(x==1);
}
static int x=0;
}
有多种方法,例如您可以执行以下操作:
There are various approaches, for example you could do the following:
第一遍可以查找所有变量声明,第二遍查找方法声明等,直到最后一遍使用所有这些信息来编译最终代码.
The first pass could look for all variable declarations, the second for method declarations, etc. until the last pass uses all this information to compile the final code.
这篇关于编译循环依赖是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!