在我们研究Pascal编程语言的基本构建块之前,让我们看一下最小的Pascal程序结构,以便我们在接下来的章节中作为参考.
Pascal程序基本上由以下部分组成 :
程序名称
使用命令
类型声明
常量声明
变量声明
函数声明
程序声明
主程序块
每个区块内的陈述和表达
评论
每个pascal程序通常都有一个标题声明,一个声明和严格按照该顺序执行部分.以下格式显示了Pascal程序的基本语法 :
program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block }
以下是一个简单的pascal代码,可以打印"Hello,World!" :
program HelloWorld; uses crt; (* Here the main program block starts *) begin writeln('Hello, World!'); readkey; end.
这将产生以下结果 :
Hello,World!
让我们看一下上述程序的各个部分 :
程序的第一行程序HelloWorld; 表示程序的名称.
第二行程序使用crt; 是一个预处理器命令,它告诉编译器在进行实际编译之前包含crt单元.
begin和end语句中包含的下一行是主程序块. Pascal中的每个块都包含在 begin 语句和 end 语句中.但是,表示主程序结束的结束语句之后是句号(.)而不是分号(;).
主程序块的开始语句是程序执行开始的地方.
编译器将忽略(* ... *)中的行,并在程序中添加注释 .
语句 writeln('Hello,World!'); 使用Pascal中可用的writeln函数导致消息"Hello ,世界!"要显示在屏幕上.
语句 readkey; 允许显示暂停,直到用户按下某个键.它是crt单元的一部分.一个单元就像是Pascal中的一个库.
最后一个语句结束.结束你的程序.
打开文本编辑并添加上述代码.
将文件另存为 hello.pas
打开命令提示符并转到保存文件的目录.
按命令键入fpc hello.pas提示并按Enter键编译代码.
如果代码中没有错误,命令提示符将带您到下一行并生成 hello 可执行文件和 hello.o 目标文件.
现在,输入 hello 在命令提示符下执行你的程序.
你将能够在屏幕上看到"Hello World",程序会一直等到你按任意键.
$ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World!
确保免费的pascal编译器 fpc 在您的路径中,并且您在包含源文件hello的目录中运行它. PAS.