How does compiling circular dependencies work?

前端 未结 2 1256
无人及你
无人及你 2020-12-01 21:17

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

You have 2 files. First, M.java:

public         


        
相关标签:
2条回答
  • 2020-12-01 21:33

    You need to take a 2-pass, or multi-pass approach:

    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.

    0 讨论(0)
  • 2020-12-01 21:50

    The first file doesn't need to know anything about XType except that it is a type, and similarly for MType in the second file. Also, in Java, all objects are effectively the same size (because everything is accessed through references), so the size of the object is not needed. This is not so in other languages - your code as it stands would not compile in C++, for example (language syntax apart).

    0 讨论(0)
提交回复
热议问题