开发者

How do C self-hosts itself?

Anyone knows the complete chain of operations from .c source code to finally an executable .exe?

I've downloaded the source of gcc,and found its c-parser.y is also written in c:

extdef:
    fndef
    | datadef
    | ASM_KEYWORD '(' expr ')' ';'
        { STRIP_NOPS ($3);
          if ((TREE_CODE ($3) == ADDR_EXPR
               && TREE_CODE (TREE_OPERAND ($3, 0)) == STRING_CST)
              || TREE_CODE ($3) == STRING_CST)
            assemble_asm ($3);
          else
            error ("argument of 开发者_高级运维`asm' is not a constant string"); }
    | extension extdef
        { pedantic = $<itype>1; }
    ;

So anyone knows the complete story of c's self-hosting?

UPDATE

I know how some compilers for scripts are written,most of them depends on c compilers.

So I'm now asking how c compiler works.


GCC has a multi-stage process, but starts with a working C compiler (which might or might not be another version of GCC).

  1. Use the other C compiler to create a first version of GCC - the GNU C Compiler.
    • This gives you a working copy of the new version of GCC (assuming the old compiler was serviceable).
    • It is not, however, identical the compiler that (the new version of) GCC would produce, except by implausible accident.
  2. Use the first version of GCC to create a second version of GCC.
    • The second version of GCC is the (obviously) the code that GCC would generate. This is the benchmark version.
    • However, it has not yet been shown that this is stable.
  3. Use the second version of GCC to create a third version of GCC.
    • The second version of GCC should produce the same output for the third version of GCC.
  4. Ensure that the second and third versions of GCC are the same.
    • On some platforms, the object files contain compilation times; clearly, the compilation time has to discount differences in compilation time.
    • Assuming that the second and third versions are 'the same', then we know that GCC can produce itself from its own source code.
    • It is now safe to use the new version of GCC to build the various runtime libraries, and the other compilers in the family.
  5. Build the other parts of the GNU Compiler Collection with the new C compiler.
    • Most people do not restrict the GNU Compiler Collection to just the C compiler.
    • Typically, they also produce the C++ and Java (and usually Objective C) compilers too.
    • And you need the Standard C++ Library support too.
    • Usually, the C compiler uses the C library provide by the platform.


You are surprised that the C compiler is written in C? What other language would a C expert use when writing his compiler?

The apparent chicken-and-egg problem only occurred once, a long time ago, when there was no compilers available at all. Then someone had to write one in assembly (after someone else wrote the first assembler in machine code :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜