Think OS 第一章

1.1 编译和解释语言

人们常常描述编程语言或者为可编译的,这会将程序翻译为机器语言然后由硬件执行;或者解释语言,它意味着程序会被软件解释器读取和执行。例如:C语言被认为编译型语言,而Python被认为是解释型语言。但是二者区别不是经常很好划分的。

首先,需要语言可以编译或者解释。例如,有C解释器和Python编译器。其次,java采用hybird方法,编译程序到一种解释予以,然后在解释器上运行翻译过的程序。Java用一种叫做Java字节码的中间语言,类似机器语言,但是在软件解释器(Java虚拟机)上运行。

因此解释型和编译型不是语言的本质区别,然而二者还是有一些基本区别。

1.2 静态类型

编译型语言常常有静态类型,这意味着你可以看代码知道每个变量指向什么。解释型语言常常有动态类型,意味着你不会知道变量的类型直到运行时。一般来说,静态 指的是发生在编译期,动态指的是运行期发生的事情。
例如,在python你可以像这样写函数:

def foo(x, y):
return x + y

看这段代码,你不能说出x,y将会指向的类型。在运行时,这个函数可以用不同类型实参调用多次。任何支持+运算的类型都是可以的,当然不满足的将会抛出运行时错误。

在C里,你将会看到类似的函数:

int foo(int x, int y) {
return x + y;
}

函数第一行包含参数的类型声明和返回值类型。x,y声明为int,意味着我们可以在编译期检查参数是否合法。

因为这些声明,当此函数被调用,编译期将会检查提供的参数是否有正确的类型,然后返回值类型是否正确。

这些检查在程序开始执行前,因此错误会被快速发现,更重要的是,错误可以在程序没有运行前发现。这些检查不必发生在运行期,因为这些原因编译型语言比解释型语言运行快。

在编译期声明类型也节省空间。在动态语言里,在程序运行时变量名被存储在内存。例如,在python里,内建函数内置返回一个包含变量名字和他们值的字典。下面是python解释器的一个例子:
>>> x = 5
>>> print locals()
{'x': 5, '__builtins__': <module '__builtin__' (built-in)>,
'__name__': '__main__', '__doc__': None, '__package__': None}(这些东东因为debug目的被加在编译器里)

注:剩下的明天抽时间翻译。

1.3 The compilation process
As a programmer, you should have a mental model of what happens during
compilation. If you understand the process, it will help you interpret error
messages, debug your code, and avoid common pitfalls.
The steps of compilation are:
1. Preprocessing: C is one of several languages that include “preprocessing
directives” that take effect before the program is compiled. For
example, the #include directive causes the source code from another
file to be inserted at the location of the directive.
2. Parsing: During parsing, the compiler reads the source code and
builds an internal representation of the program, called an “abstract
syntax tree.” Errors detected during this step are generally syntax errors.
3. Static checking: The compiler checks whether variables and values
have the right type, whether functions are called with the right number
and type of arguments, etc. Errors detected during this step are
sometimes called “static semantic” errors.
4. Code generation: The compiler reads the internal representation of the
program and generates machine code or byte code.
5. Linking: If the program uses values and functions defined in a library,
the compiler has to find the appropriate library and include the required
code.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值