如何编译循环依赖项工作? [英] How does compiling circular dependencies work?

查看:101
本文介绍了如何编译循环依赖项工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以Java为例,但我认为(未测试过)它在其他(所有)语言中都有效。

I've made the example in Java but I think (not tested) that it works in other (all?) languages.

首先, 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;}
}

Ok它是坏的编程,但如果你运行 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或任何其他编译器,你知道)管理

Probably this is a stupid question, but 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遍,或多遍方法:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆