A Pascal program can consist of multiple modules called units or modules within Pascal. A unit in Pascal may comprise various code blocks formed from variables and type declarations, commands, procedures, etc. Pascal offers numerous built-in units, enabling programmers to define and write their own units for use in other programs.
Utilizing built-in units, or modules, in Pascal
Both pre-defined and user-defined units are incorporated into the program using statements. In this article, Mytour will elucidate how to create and add user-defined units. Firstly, learn how to include the pre-defined unit crt into your program.
program myprog;
uses crt;
The following example illustrates the usage of the crt unit:
Creating and Utilizing Units in Pascal
To create a unit in Pascal, you must write modules or subprograms that you want to store within it and save it as a file with the extension .pas. The first line of the file must start with the Unit keyword + the name of the unit. For example:
unit calculateArea;
Below are 3 crucial steps to create a unit in Pascal:
- The filename must match the unit name. Therefore, in the example above, the unit calculateArea will be saved in a file named calculateArea.pas.
- The next line includes the interface keyword. After this line, you write declarations for all the functions and procedures that will be integrated into the unit.
- Immediately after the function declarations, you add the implementation keyword. After the line containing the implementation keyword, provide definitions for all the subprograms.
The following program example creates a unit named calculateAre:
Next, write a simple program using the unit defined above:
When the above code is compiled and executed, it will return the following result:
Here, Mytour has just introduced you to Units in Pascal. Additionally, you can read more about Pascal functions, compiling common functions often encountered in Pascal to quickly become familiar with the Pascal programming language. To learn about dates and times in Pascal, readers should not forget to read the next articles in the Pascal series on Mytour.