关于编译器的基本课程

A basic lesson about compilers

几个月来,我试图了解编译器的工作原理。现在我不关心语法分析、将其拆分为标记并创建 AST。我想专注于可执行文件的创建。据我所知,编译器将代码拆分并将其翻译成汇编指令,然后以某种方式将其转换为可执行代码。

我想为自定义编程语言创建一个基本的编译器。这样做的唯一可能性是采用汇编程序,将我的源代码转换为汇编语言然后进行汇编吗?或者是否可以在不使用第三方工具的情况下创建可执行文件。我的项目唯一缺少的代码片段是 EXE 文件是如何从汇编指令创建的。

我知道这是一个很复杂的话题。这就是为什么我一直在寻找创建跨平台编译器的技术。我还想知道是否可以使用像 g++ 这样的编译器,将我的代码转换为 C++ 代码并使用 g++。那是一个替代计划,但仍然不是我想要创建的。我是否必须为每个单独的处理器架构编写一个编译器/汇编器,我基本上该怎么做?经过几个月的研究,我终于决定去问问对这个话题有更好了解的人。

希望你能点亮我的心。 :)

问候 BraunBerry

你的问题大部分是题外话。不过关于编译的好书是The Dragon Book. (And you could also read Scott's Programming Language Pragmatics and Queinnec's Lisp In Small Pieces)

As far as I know, compilers split the code up and translate it into assembly instructions, which are then somehow transformed into executable code.

比这复杂得多。编译器实际上(多次)将optimization purposes (and optimization is an important but difficult topic, and that is why there are few C compilers).. For example, most of GCC optimization passes (GCC has hundreds of them) are transforming Gimple的一些内部表示转换为Gimple (例如 inlining, loop unrolling,等等)。

That's why I was looking for techniques to create a cross platform compiler. I also wondered if I could take a compiler like g++, transform my code into C++ code and compiling it with g++.

一般来说,很多人都在使用 C 作为可移植的目标编程语言,而不是 C++。 This answer 解释更多。实际上,可能很难生成 真正的 好闻的 C++ 代码(例如使用 C++ 容器和智能指针)。最后,您的系统 C++ 编译器可能需要大量时间来编译生成的 C++ 代码(换句话说,C++ 编译速度很慢)。

Or is it possible to create executables without using third party tools.

这可能是可能的,但为什么要避免使用第三方工具?请注意,许多编译器至少使用汇编器和链接器(并且都符合 "third party tools")。如果您选择生成 C(可能是一个不错的选择),您将使用的 C 编译器是第三方工具(而​​且是一个相当大的工具!)。

如果你想直接自己生成可执行文件(我不建议这样做,工作量很大),你需要准确地理解file format of executables (which is operating system specific), such as ELF or PE. I recommend Levine's book Linkers and Loaders. You may also need to understand how to do system calls for your OS (so read Operating Systems: Three Easy Pieces), and you'll need to implement some standard library for your language. And dynamic linking使事情变得复杂。

并且您可以考虑使用 JIT 翻译库,例如 libgccjit and others (mentioned here)。

Do I have to write a compiler / an assembler for each individual processor architecture and how can i do this basically?

大多数编译器通过定义一些目标中立的中间表示来处理这个问题(例如 GCC 的 Gimple)。大多数优化都是在(并使用)该中间表示上完成的。

PS。对于您的情况,我强烈建议为 Linux 及更高版本构建编译器,因为 Linux 由 free software whose source code you can study. If you use Windows, which is proprietary software, some details are not public and are important to you, and you'll need a lot of time to reverse-engineer 个组成。