37 min read

In which we turn your computer into a Pascal development workshop, compile our first program, and discover why the compilation step is not an inconvenience but a superpower.

Learning Objectives

  • Download and install Free Pascal on Windows, macOS, and Linux
  • Download and install the Lazarus IDE
  • Write, compile, and run a 'Hello, World!' program from the command line
  • Write, compile, and run a program using the Lazarus IDE
  • Understand the compile-link-execute cycle and what makes Pascal a compiled language

Chapter 2: Setting Up: Free Pascal, Lazarus, and Your First Program

In which we turn your computer into a Pascal development workshop, compile our first program, and discover why the compilation step is not an inconvenience but a superpower.


There is a particular satisfaction in the moment a program you wrote compiles for the first time. Not runs — compiles. The compiler reads your code, checks every declaration, verifies every type, ensures every semicolon is in its place, and then, if you have been honest with it, produces a standalone executable file that needs nothing else to run. No interpreter. No runtime. No virtual machine. Just a binary that your operating system can execute directly.

That moment is ahead of you, and it is closer than you think.

This chapter walks you through every step of setting up a modern Pascal development environment. We will install the Free Pascal Compiler — the open-source, cross-platform compiler that targets more than twenty processor and operating-system combinations. We will install the Lazarus IDE, the visual development environment that gives you a professional code editor, an integrated debugger, and a form designer for building graphical applications. And then we will write, compile, and run our first Pascal program — first from the command line, then from within Lazarus.

Along the way, you will learn what happens during compilation, why it matters, and how the compile-link-execute cycle gives you information that interpreted languages simply cannot provide.

Let us get to work.


2.1 What You Will Need

Before we install anything, let us take stock of what you need.

Hardware. Any computer manufactured in the last fifteen years will do. Free Pascal is remarkably lightweight — the compiler itself is a single executable, and even the full Lazarus IDE installation occupies less than a gigabyte of disk space. If your computer can run a modern web browser, it can compile Pascal programs with room to spare.

Operating system. Free Pascal supports Windows (7 and later, including Windows 10 and 11), macOS (10.10 Yosemite and later, including Apple Silicon Macs with M1/M2/M3/M4 chips), and Linux (any reasonably modern distribution — Ubuntu, Fedora, Debian, Arch, and many others). It also supports FreeBSD, and there are experimental ports for other platforms. This chapter provides detailed instructions for the three major platforms.

A text editor (optional but recommended). While Lazarus includes a full code editor, you will sometimes want to write quick programs in a lightweight editor — especially in the first few chapters, where our programs are short enough that launching a full IDE feels like driving a semi-truck to the corner store. Any text editor will work:

  • Windows: Notepad++ (free), VS Code, or even the built-in Notepad
  • macOS: TextEdit (in plain text mode), BBEdit (free version), VS Code
  • Linux: gedit, kate, nano, vim, VS Code

The key requirement is that the editor saves files as plain text with the .pas extension. Do not use a word processor like Microsoft Word or Google Docs — they embed formatting codes that the compiler cannot understand.

A terminal or command prompt. You will need access to a command line interface:

  • Windows: Command Prompt (cmd) or PowerShell — both come pre-installed. We recommend PowerShell.
  • macOS: Terminal.app, found in Applications > Utilities.
  • Linux: Your distribution's terminal emulator (GNOME Terminal, Konsole, xterm, or similar).

If you have never used a command line before, do not worry. We will walk through every command you need, and by the end of this chapter, you will be comfortable navigating to a directory and running a compiler.

💡 Intuition Builder: Think of the command line as a conversation with your computer. Instead of pointing and clicking, you type what you want. It is more precise, more powerful, and — once you get used to it — surprisingly faster for tasks like compiling code.

Disk space. Plan for approximately 1 GB total: around 100 MB for the Free Pascal Compiler alone, and 500-800 MB for the full Lazarus IDE installation including its component library. You will also need a working directory for your source files, but Pascal source code is tiny — a typical program file is just a few kilobytes.


2.2 Installing Free Pascal

Free Pascal (often abbreviated FPC) is an open-source compiler for the Pascal and Object Pascal languages. It is developed by a dedicated team of volunteers, has been in active development since 1993, and produces optimized native code for an impressive range of platforms: Windows, macOS, Linux, FreeBSD, ARM (including Raspberry Pi), and many more.

📊 Real-World Application: Free Pascal is not a toy or a historical curiosity. It is the compiler behind Lazarus, which is used to build production software worldwide. The popular game engine Castle Game Engine is built with Free Pascal. PeaZip, a file archiver with millions of users, is a Lazarus application. Free Pascal powers embedded systems, scientific computing tools, and enterprise database applications in production today.

The current stable release as of this writing is Free Pascal 3.2.2, with version 3.2.4 in development. Any version 3.2 or later will work perfectly for this textbook.

Windows Installation

Step 1: Download the installer.

Open your web browser and navigate to https://www.freepascal.org/download.html. Click on the link for the Windows installer. You will typically see options for "i386-win32" (32-bit) and "x86_64-win64" (64-bit). If you are running a 64-bit version of Windows (which is almost certain on any modern machine), choose the x86_64-win64 version. The download is approximately 50 MB.

⚠️ Common Pitfall: Do not download the "cross-compilation" packages unless you know you need them. For learning, the standard installer for your platform is all you need.

Step 2: Run the installer.

Double-click the downloaded .exe file. If Windows displays a User Account Control (UAC) prompt asking "Do you want to allow this app to make changes to your device?", click Yes. The Free Pascal installer uses a standard setup wizard.

  • Welcome screen: Click Next.
  • License agreement: Read the license (Free Pascal is released under the LGPL with a static linking exception — meaning you can distribute programs you compile without any licensing complications). Click Next.
  • Installation directory: The default is usually C:\FPC\3.2.2\ or similar. We recommend keeping the default. Click Next.
  • Components: Keep the defaults. The installer selects the compiler, RTL (Run-Time Library), utilities, and documentation. Click Next.
  • Start Menu folder: Keep the default or choose your own. Click Next.
  • Additional tasks: Check "Add Free Pascal directory to PATH" if this option appears. This is important — it allows you to run fpc from any command prompt. Click Next.
  • Install: Click Install and wait for the process to complete. It usually takes less than a minute.
  • Finish: Click Finish.

Step 3: Verify the installation.

Open a new Command Prompt or PowerShell window. Type:

fpc -v

You should see output similar to:

Free Pascal Compiler version 3.2.2 [2021/05/15] for x86_64
Copyright (c) 1993-2021 by Florian Klaempfl and others

If you see this, congratulations — Free Pascal is installed and ready.

🐛 Debugging Spotlight: If the command fpc is not recognized, the compiler's bin directory was not added to your system's PATH. To fix this: 1. Open Settings > System > About > Advanced system settings (or search for "Environment Variables" in the Start menu). 2. Under System variables, find Path and click Edit. 3. Click New and add the path to the Free Pascal bin directory — typically C:\FPC\3.2.2\bin\i386-win32\ or C:\FPC\3.2.2\bin\x86_64-win64\. 4. Click OK on all dialogs. 5. Close and reopen your terminal. The PATH change does not take effect in terminals that were already open. Try fpc -v again. It should now work.

macOS Installation

Step 1: Download the installer.

Navigate to https://www.freepascal.org/download.html and select the macOS download. For Macs with Apple Silicon (M1, M2, M3, M4 chips), choose the aarch64-darwin package. For older Intel Macs, choose x86_64-darwin. If you are unsure which you have, click the Apple menu > About This Mac — if the "Chip" line says "Apple M1" (or M2, M3, M4), you have Apple Silicon.

The download is a .dmg disk image, approximately 40 MB.

Step 2: Install the package.

Double-click the downloaded .dmg file to mount it. Inside, you will find an installer package (.pkg file). Double-click it to launch the installer.

macOS may show a warning: "This package is from an unidentified developer." If this happens:

  1. Open System Settings > Privacy & Security.
  2. Scroll down — you should see a message about the blocked installer with an "Open Anyway" button.
  3. Click Open Anyway and confirm.

Follow the installer prompts (Introduction, License, Destination, Install). The default installation location is /usr/local/lib/fpc/ with the compiler binary placed in /usr/local/bin/.

Step 3: Verify the installation.

Open Terminal (Applications > Utilities > Terminal) and type:

fpc -v

You should see the version information just as on Windows. If the command is not found, try:

/usr/local/bin/fpc -v

If that works but the short form does not, add /usr/local/bin to your PATH by editing your shell profile:

echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

(If you use bash instead of zsh, replace .zshrc with .bash_profile.)

⚠️ Common Pitfall (macOS Catalina and later): Apple requires developers to notarize their applications. If the FPC installer refuses to open, use the System Settings > Privacy & Security workaround described above. This is a macOS security feature, not a problem with Free Pascal.

Linux Installation

On Linux, Free Pascal is available through most distribution package managers, which is the easiest installation method.

Ubuntu / Debian:

sudo apt update
sudo apt install fp-compiler fp-units-rtl fp-units-base

This installs the compiler and essential units. The download is approximately 70 MB.

Fedora:

sudo dnf install fpc

Arch Linux:

sudo pacman -S fpc

Verify the installation (same on all distributions):

fpc -v

⚠️ Common Pitfall: Distribution package managers sometimes ship older versions of Free Pascal. If your distribution provides version 3.0.x instead of 3.2.x, you can download the latest version directly from the Free Pascal website. The Linux installer is a .tar archive with an install script: extract it, run ./install.sh, and follow the prompts. The direct download gives you the newest release regardless of what your distribution packages.

Alternative: Install from the official tarball.

If you prefer the latest version:

  1. Download the appropriate tarball from https://www.freepascal.org/download.html (choose your architecture: x86_64-linux for 64-bit, aarch64-linux for ARM64).
  2. Extract: tar -xf fpc-3.2.2.x86_64-linux.tar
  3. Run the installer: cd fpc-3.2.2.x86_64-linux && sudo ./install.sh
  4. Accept the default installation prefix (/usr/local).
  5. Verify with fpc -v.

🔄 Check Your Understanding: Before moving on, make sure you can open a terminal on your system and see the Free Pascal version string when you run fpc -v. If you cannot, revisit the troubleshooting steps for your platform above. Everything that follows in this chapter — and this entire textbook — depends on having a working Free Pascal installation.


2.3 Installing the Lazarus IDE

Lazarus is a free, open-source Integrated Development Environment (IDE) for Free Pascal. If Free Pascal is the engine, Lazarus is the workshop: it provides a code editor with syntax highlighting and code completion, an integrated debugger, a visual form designer for building graphical user interfaces, and a project manager for organizing multi-file applications.

You do not need Lazarus for the first several parts of this textbook — we will write console programs using a text editor and the command-line compiler through Part IV. But Lazarus becomes essential in Part V (GUI Programming), and installing it now means you always have the option of using a powerful IDE. Many students find they prefer it even for console programs.

📊 Real-World Application: Lazarus is a full-featured RAD (Rapid Application Development) environment modeled on Delphi, the commercial Pascal IDE that powered millions of Windows applications in the 1990s and 2000s (and is still actively developed by Embarcadero). Lazarus can build native GUI applications for Windows, macOS, and Linux from a single codebase — the same source, recompiled on each platform. This is true native cross-platform development, not a web wrapper pretending to be a desktop app.

Windows Installation

Step 1: Download Lazarus.

Navigate to https://www.lazarus-ide.org/index.php?page=downloads. Download the Windows installer. The file is approximately 200-300 MB. Make sure you download the version that matches your Free Pascal installation (32-bit or 64-bit).

Step 2: Run the installer.

The Lazarus installer follows the same pattern as the FPC installer:

  • Accept the UAC prompt.
  • Read and accept the license (Lazarus is also GPL/LGPL licensed).
  • Choose the installation directory (default: C:\Lazarus\).
  • Select components — keep the defaults.
  • Choose a Start Menu folder.
  • Click Install.

The installation takes a few minutes as Lazarus compiles its component library during setup.

⚠️ Common Pitfall: If you installed Free Pascal separately before installing Lazarus, and then install Lazarus (which bundles its own copy of FPC), you may end up with two FPC installations. This is generally harmless — Lazarus uses its bundled copy. But be aware that the fpc command in your terminal may point to the standalone installation rather than the Lazarus-bundled one. For our purposes, either copy works fine.

Step 3: First launch.

Launch Lazarus from the Start Menu. On first launch, Lazarus may take a minute to compile additional components. You will see a multi-window layout:

  • Main window (top): The menu bar, toolbar, and component palette.
  • Source Editor (center): Where you write code. It opens with a default project.
  • Object Inspector (left): Shows properties of selected visual components.
  • Messages (bottom): Compilation output, errors, and warnings.
  • Form Designer: A blank form (window) for visual GUI design.

For now, just confirm that Lazarus opens without errors. We will use it shortly.

macOS Installation

Step 1: Download Lazarus.

From the Lazarus download page, get the macOS package. There are separate builds for Intel and Apple Silicon Macs — choose the correct one for your hardware.

Step 2: Install.

Open the .dmg and drag the Lazarus application to your Applications folder. On first launch, macOS will likely block the application because it is from an "unidentified developer." Use the same Privacy & Security workaround as for Free Pascal: open System Settings > Privacy & Security, find the blocked app, and click Open Anyway.

Step 3: Command-line tools.

Lazarus on macOS requires the Xcode Command Line Tools. If you do not have them installed, open Terminal and run:

xcode-select --install

A dialog will appear asking you to install the tools. Click Install and wait for the download (approximately 1-2 GB). This provides the linker and other build tools that Lazarus needs.

⚠️ Common Pitfall (macOS): After a major macOS update (e.g., upgrading from Ventura to Sonoma), the Xcode Command Line Tools sometimes need to be reinstalled. If Lazarus suddenly cannot compile anything after an OS update, try running xcode-select --install again.

Linux Installation

Ubuntu / Debian:

sudo apt install lazarus

This installs Lazarus and, if not already present, Free Pascal as a dependency.

Fedora:

sudo dnf install lazarus

Arch Linux:

sudo pacman -S lazarus

Launch Lazarus from your application menu or by typing lazarus-ide (or startlazarus) in a terminal.

First-Launch Walkthrough

Regardless of your platform, the first time you open Lazarus you will see the multi-window IDE layout described above. Here is a brief orientation — we will explore each part in depth when we use it:

  1. The Menu Bar provides access to File, Edit, Search, View, Project, Run, Package, Tools, Window, and Help menus. The most important items for now: File > New to create projects, and Run > Run (or press F9) to compile and execute.

  2. The Component Palette runs along the top of the main window and contains tabs full of visual components (buttons, labels, text fields, and more). We will not use these until Part V.

  3. The Source Editor is where you will spend most of your time. It features syntax highlighting (Pascal keywords in bold, strings in color, comments in italics), code folding, bracket matching, code completion (press Ctrl+Space), and an integrated help system (press F1 on any keyword).

  4. The Object Inspector on the left shows properties and events for selected visual components. For console programs, you can minimize or close this window.

  5. The Messages window at the bottom shows compiler output. When you compile, success or failure messages appear here — including the exact line and column of any errors.

Best Practice: Before you start writing code, go to Tools > Options > Editor > General and verify that Tab Width is set to 2 (the Pascal convention) and that Smart Tabs is enabled. Also check Tools > Options > Editor > Display and ensure Show Line Numbers is enabled. These small settings will make your editing experience much smoother.


🔄 Check Your Understanding: Can you open Lazarus and see the Source Editor, Object Inspector, and Messages windows? If Lazarus fails to start, check that Free Pascal is correctly installed — Lazarus depends on it. On Linux, missing dependencies sometimes prevent launch; check terminal output for error messages about missing libraries.


2.4 Your First Program: Hello, World! (Command Line)

The tradition of beginning with "Hello, World!" dates back to Brian Kernighan and Dennis Ritchie's 1978 book The C Programming Language. It is a fine tradition: the program is trivial enough that you can focus entirely on the mechanics of writing, saving, compiling, and running — without worrying about logic.

Here is the complete program:

program HelloWorld;
{ Our first Pascal program.
  It prints a greeting to the screen and exits. }
begin
  WriteLn('Hello, World!');
end.

That is the entire program. Six lines. Let us walk through what each part means:

  • program HelloWorld; — The program header. It gives our program a name. The name must follow Pascal's identifier rules (starts with a letter, contains only letters, digits, and underscores). The semicolon terminates the declaration.

  • { Our first Pascal program. ... } — A comment. Everything between { and } is ignored by the compiler. Comments are for humans. Use them to explain why your code does what it does.

  • begin — Marks the start of the program's executable section. Think of it as "start here."

  • WriteLn('Hello, World!'); — The statement that does the work. WriteLn is a built-in procedure that writes text to the screen and then moves to a new line. The text 'Hello, World!' is a string literal, enclosed in single quotes (not double quotes — Pascal always uses single quotes for strings). The semicolon ends the statement.

  • end. — Marks the end of the program. Note the period after end — not a semicolon. The period tells the compiler "this is the end of the entire program." Every Pascal program ends with end. and a period.

💡 Intuition Builder: A Pascal program has a rigid but simple skeleton: a header that names it, a body between begin and end. that contains the executable statements, and optionally declarations (variables, constants, procedures) between the header and begin. This structure is not arbitrary — it is the language enforcing Wirth's principle that programs should declare their intentions clearly before acting on them.

Writing the Program

Open your text editor (Notepad++, VS Code, nano, or whatever you chose). Type the program exactly as shown above. Save it as hello.pas in a convenient location. We recommend creating a dedicated folder for your Pascal work:

  • Windows: C:\PascalProjects\ (or C:\Users\YourName\Documents\PascalProjects\)
  • macOS: ~/PascalProjects/
  • Linux: ~/PascalProjects/

Compiling the Program

Open your terminal and navigate to the directory where you saved hello.pas:

Windows (PowerShell):

cd C:\PascalProjects

macOS / Linux:

cd ~/PascalProjects

Now compile:

fpc hello.pas

If everything is correct, you will see output similar to:

Free Pascal Compiler version 3.2.2 [2021/05/15] for x86_64
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Win64 for x86-64
Compiling hello.pas
Linking hello.exe
8 lines compiled, 0.1 sec

The key line is "8 lines compiled" followed by the linking message. The compiler read your source code, translated it into machine code, and the linker combined it with the runtime library to produce an executable file.

Look at your directory now. You will find:

  • hello.pas — Your source code (unchanged).
  • hello.o — The object file (intermediate compilation output). You can delete this; it is a byproduct.
  • hello.exe (Windows) or hello (macOS/Linux) — The executable. This is your program.

Running the Program

Windows:

.\hello.exe

macOS / Linux:

./hello

Output:

Hello, World!

There it is. You wrote a program. The compiler checked it. The linker assembled it. The operating system ran it. And it printed exactly what you asked it to print.

📊 Real-World Application: That executable you just created is a standalone native binary. On Windows, hello.exe is approximately 150-400 KB. You can copy it to another Windows machine and run it without installing anything — no Free Pascal, no runtime, no framework. Try that with a Python script or a Java program. This is what Theme 4 means by "native compiled code matters." The programs you build with Pascal are self-contained.

Now let us try a small variation. Edit hello.pas to add a second line of output:

program HelloWorld;
begin
  WriteLn('Hello, World!');
  WriteLn('My name is [your name here].');
  WriteLn('I am learning Pascal!');
end.

Save the file, recompile with fpc hello.pas, and run again. You should see three lines of output. Notice that each WriteLn call produces one line — WriteLn stands for "Write Line."

🐛 Debugging Spotlight: If the compiler reports an error, read the message carefully. Common first-program errors: - "Fatal: Cannot open file 'hello.pas'" — You are in the wrong directory. Use cd to navigate to where you saved the file. - "hello.pas(4,3) Fatal: Syntax error, '.' expected but 'IDENTIFIER' found" — You may have a typo in a keyword, or forgotten a semicolon on the previous line. - "hello.pas(3,12) Error: Illegal character in input" — You may have used "smart quotes" (curly quotes) instead of straight single quotes. Make sure your editor is in plain text mode. The error message tells you the file name, the line number, and the column number in parentheses. Go to that line. The error is almost always there — or on the line immediately before it.


🔄 Check Your Understanding: Make sure you can compile and run the Hello World program before continuing. If you are stuck, jump ahead to Section 2.8 for a comprehensive troubleshooting guide, then come back here.


2.5 Your First Program in Lazarus

Now let us do the same thing using the Lazarus IDE. The experience is different — more visual, more guided — but the underlying process is identical: you write source code, the compiler (the same Free Pascal compiler) translates it, and you get an executable.

Step 1: Create a new project.

In Lazarus, go to Project > New Project. A dialog appears with several project types:

  • Application — A GUI application with a main form (window). We will use this in Part V.
  • Simple Program — A console program with just program, begin, and end.
  • Program — A console program with a uses clause.
  • Console Application — A console program using the SysUtils unit.

Choose Simple Program and click OK.

Lazarus creates a new project and opens it in the Source Editor. You will see something like:

program Project1;

begin
end.

Step 2: Rename the project.

Go to Project > Save Project As. Navigate to your PascalProjects directory (create it if necessary). Save the file as hello_lazarus.lpi. Lazarus creates two files: hello_lazarus.lpi (the project file, which stores project settings in XML) and hello_lazarus.lpr (the source file — lpr stands for "Lazarus Project," but it is standard Pascal source code).

Step 3: Write the program.

In the Source Editor, modify the code to:

program hello_lazarus;

begin
  WriteLn('Hello from Lazarus!');
  WriteLn('This program was compiled with Free Pascal via the Lazarus IDE.');
end.

Step 4: Compile and run.

Press F9 (or go to Run > Run). Lazarus compiles the program and runs it. For a console program, a terminal window will briefly appear showing the output — and then immediately close. This happens because the program finishes instantly and the terminal closes.

To keep the terminal open so you can read the output, add a ReadLn call at the end:

program hello_lazarus;

begin
  WriteLn('Hello from Lazarus!');
  WriteLn('This program was compiled with Free Pascal via the Lazarus IDE.');
  ReadLn;  { Wait for the user to press Enter before closing }
end.

Press F9 again. Now the terminal window stays open until you press Enter.

Best Practice: For console programs in Lazarus, always add a ReadLn; at the end during development so you can see the output. Remove it when you are building a program meant to be run from an existing terminal window.

Step 5: Find the executable.

Lazarus places the compiled executable in the same directory as the project file (by default). Navigate to your PascalProjects directory and you will find hello_lazarus.exe (Windows) or hello_lazarus (macOS/Linux). You can run it from the command line just like the program we compiled manually.

Command Line vs. IDE: Which Should You Use?

Both approaches use the same compiler and produce identical executables. The choice is a matter of workflow preference:

Feature Command Line (fpc) Lazarus IDE
Startup time Instant A few seconds
Good for Quick programs, scripts, learning Larger projects, GUI apps
Error navigation Read line numbers in terminal Click error to jump to line
Debugging Manual WriteLn statements Integrated debugger with breakpoints
Project management Manual (you organize files) Automatic (project files track everything)
GUI development Not possible Full visual form designer

For Parts I through IV of this textbook, either approach works. Use whichever feels more comfortable. Many experienced Pascal programmers use both: the command line for quick tests and Lazarus for serious projects.


2.6 Understanding the Compilation Process

When you ran fpc hello.pas, several things happened behind the scenes. Understanding this process is essential — not because you need to know the details to write Pascal programs, but because the compilation model is one of Pascal's fundamental advantages.

The Three-Stage Pipeline

The journey from source code to running program has three distinct stages:

Stage 1: Compilation (Source Code to Object Code)

hello.pas  ──→  [ Free Pascal Compiler ]  ──→  hello.o
(your code)         (fpc)                    (object file)

The compiler reads your .pas file character by character. It performs lexical analysis (breaking the text into tokens: keywords, identifiers, literals, operators), syntactic analysis (checking that the tokens form valid Pascal statements), and semantic analysis (checking types, verifying that identifiers are declared, ensuring operations make sense). If any check fails, the compiler reports an error and stops.

If all checks pass, the compiler generates object code — a .o file containing machine instructions for your specific processor, but not yet a complete program.

Stage 2: Linking (Object Code to Executable)

hello.o     ──→  [ Linker ]  ──→  hello.exe
(your code)      (ld)            (executable)
   +
system.o
(runtime library)

The linker combines your object code with the runtime library (RTL) — pre-compiled code that provides built-in procedures like WriteLn, ReadLn, memory management, string handling, and the program startup/shutdown code. The result is a complete, standalone executable.

Stage 3: Execution

hello.exe  ──→  [ Operating System ]  ──→  "Hello, World!"
(executable)     (Windows/macOS/Linux)     (screen output)

The operating system loads the executable into memory and begins executing the machine instructions. No compiler needed. No runtime needed. The executable is self-contained.

💡 Intuition Builder: Think of it like writing a letter. Stage 1 (compilation) is translating the letter from English into the recipient's language. Stage 2 (linking) is putting the translated letter in an envelope with the correct address and postage. Stage 3 (execution) is the postal service delivering it. Once the letter is in the envelope, you do not need the translator anymore — the letter stands on its own.

Compiled vs. Interpreted: Why It Matters

Pascal is a compiled language. Python, JavaScript, and Ruby are interpreted languages (or use just-in-time compilation, which is a hybrid approach). The difference is fundamental:

Aspect Compiled (Pascal, C, Rust) Interpreted (Python, JS, Ruby)
When errors are caught Before running While running
Execution speed Fast (native machine code) Slower (interpreted layer)
Distribution Single executable file Source code + interpreter
Startup time Instant Interpreter must load first
Type checking At compile time At run time

The most important row in that table is the first one. When you compile a Pascal program, the compiler checks everything before producing an executable. If your program compiles, you know:

  • Every variable is declared and has a type.
  • Every type is used correctly — you cannot accidentally add a string to an integer.
  • Every procedure and function call has the correct number and types of arguments.
  • Every branch of every if statement and case statement is syntactically valid.
  • Every begin has a matching end.

This is an extraordinary amount of verification that happens before a single line of your program runs. In Python, a type error on line 500 will not be discovered until the program reaches line 500 during execution — which might be days later in production.

📊 Real-World Application: In 2019, a study by Zheng et al. analyzed bug reports in large open-source projects and found that statically-typed, compiled languages had significantly fewer type-related runtime bugs than dynamically-typed, interpreted languages. The compiler is not just a translator — it is a quality assurance inspector that works for free.

The tradeoff is the compilation step itself. Every time you change your code, you must recompile before you can run. With Free Pascal, compilation is remarkably fast — a typical program in this textbook compiles in under a second. The time you spend compiling is vastly outweighed by the time you save not debugging type errors at runtime.

There is another advantage worth mentioning: executable size and deployment simplicity. When you compile hello.pas, the resulting executable is approximately 150-400 KB depending on your platform. That file runs on any compatible machine without any additional software. Compare this to a Python script, which requires a Python installation (100+ MB) and potentially dozens of third-party packages. A Java program requires the Java Runtime Environment (150+ MB). A Node.js application requires Node (50+ MB) plus node_modules (often hundreds of megabytes).

This is not a theoretical advantage. In professional software development, deployment — getting your program onto the machines where it needs to run — is one of the most time-consuming and error-prone parts of the process. "It works on my machine" is the most dreaded sentence in software engineering. With Pascal, what you compile is what you ship. There is no dependency resolution, no version conflict, no missing package. The executable is the program.

💡 Intuition Builder: Think of a compiled executable like a printed book. Once the book is printed, you do not need the printing press, the typesetter, or the paper mill to read it. You just need the book. An interpreted program is more like a script for a play — you need the script and the actors (the interpreter) and the stage (the runtime) every time you want a performance. Both approaches have their place, but for reliability and simplicity of distribution, the printed book wins.


🔄 Check Your Understanding: In your own words, explain the difference between a compiler error and a runtime error. Which kind does Pascal catch before your program runs? If you wrote a program that tries to divide a number by zero, would that be caught at compile time or run time? (Think about it — the answer may surprise you. We will revisit this in Chapter 5.)


2.7 The Structure of a Pascal Program

Now that you have compiled and run a program, let us look more carefully at the structure every Pascal program follows. Understanding this structure now will save you hours of confusion later.

The Complete Skeleton

A Pascal program can contain all of the following sections, in this order:

program ProgramName;           { 1. Program header }

uses                           { 2. Uses clause (optional) }
  SysUtils, Classes;

const                          { 3. Constant declarations (optional) }
  MaxItems = 100;

type                           { 4. Type declarations (optional) }
  TScore = Integer;

var                            { 5. Variable declarations (optional) }
  Name: String;
  Age: Integer;

{ 6. Procedure and function declarations (optional) }
procedure SayHello;
begin
  WriteLn('Hello!');
end;

begin                          { 7. Main program block }
  SayHello;
  WriteLn('Goodbye!');
end.                           { 8. Program terminator }

Let us examine each part:

1. Program header. The program keyword followed by a name and semicolon. The name should describe what the program does. It must be a valid Pascal identifier: starts with a letter or underscore, contains only letters, digits, and underscores.

2. Uses clause. Lists the units (library modules) your program depends on. SysUtils provides string handling, date/time, and exception support. Classes provides container classes. For now, our simple programs do not need a uses clause — WriteLn and ReadLn are built into the language.

3-5. Declaration sections. Constants (const), types (type), and variables (var) must be declared before they are used. This is Pascal's "declare before use" principle — one of its core design decisions. We will explore each of these in Chapter 3.

6. Procedures and functions. Named blocks of code that perform specific tasks. We will cover these in depth in Chapter 7.

7-8. Main program block. The begin...end. block contains the statements that execute when the program runs. This is the entry point — the first statement after begin is the first thing your program does.

Comments: Three Styles

Pascal supports three comment styles:

{ This is a brace comment. It can span
  multiple lines. }

(* This is an old-style comment.
   Also multi-line. Rarely used today. *)

// This is a line comment. Everything after // to end of line is ignored.

The // style was introduced in Delphi and is supported by Free Pascal. It is the most common style for short comments. Use { } for longer block comments.

Best Practice: Comment your code to explain why, not what. The statement WriteLn('Hello'); does not need a comment saying { print hello } — that is obvious. But a comment like { Greet the user before showing the menu } explains the purpose, which is useful.

A Second Example: Hello, Name

Here is a slightly more interesting program that demonstrates string output:

program HelloName;
{ Displays a personalized greeting.
  Demonstrates multiple WriteLn calls and string concatenation. }
begin
  WriteLn('=================================');
  WriteLn('  Welcome to Pascal Programming! ');
  WriteLn('=================================');
  WriteLn;
  WriteLn('My name is Rosa Martinelli.');
  WriteLn('I am learning to program in Pascal.');
  WriteLn('Today I compiled my first program!');
  WriteLn;
  WriteLn('Pascal was designed by Niklaus Wirth in 1970.');
  WriteLn('Free Pascal keeps the language alive in ', 2026, '.');
end.

Several things to notice:

  • WriteLn; with no arguments prints a blank line.
  • WriteLn('text', 2026, '.');WriteLn accepts multiple arguments separated by commas. It prints each one in sequence. Here it prints a string, then an integer, then another string — all on the same line, followed by a newline. Pascal automatically converts the integer to its string representation.
  • The program does not declare any variables — it uses only literal values. We will add variables in Chapter 3.

💡 Coming From Python: In Python, you write print("Hello"). In Pascal, you write WriteLn('Hello');. The differences: Pascal uses single quotes for strings, requires a semicolon after each statement, and the main code lives inside a begin...end. block. Python infers everything; Pascal declares everything.

💡 Coming From C/Java: In C, you write printf("Hello\n"); or in Java, System.out.println("Hello");. Pascal's WriteLn is simpler — no format strings needed for basic output, no \n escape (WriteLn adds the newline automatically), no class.method syntax. Pascal uses ' for strings where C uses ". And the program structure (program, begin, end.) replaces C's int main() and Java's public static void main.


2.8 Common Setup Problems and Fixes

Even experienced developers occasionally struggle with environment setup. Here is a comprehensive troubleshooting guide for the most common issues.

Problem: "fpc" Is Not Recognized as a Command

Symptoms: You type fpc hello.pas and get "'fpc' is not recognized as an internal or external command" (Windows) or "command not found" (macOS/Linux).

Cause: The Free Pascal compiler's bin directory is not in your system's PATH environment variable.

Fix (Windows): 1. Find where Free Pascal is installed. Check C:\FPC\, C:\Lazarus\fpc\, or C:\Program Files\Free Pascal\. 2. Locate the bin subdirectory (e.g., C:\FPC\3.2.2\bin\x86_64-win64\). 3. Add this path to your system PATH (see the detailed instructions in Section 2.2). 4. Open a new terminal window — PATH changes do not affect already-open terminals.

Fix (macOS/Linux): 1. Check if FPC is installed in a non-standard location: which fpc or find /usr -name fpc. 2. Add the directory containing fpc to your PATH in ~/.zshrc (macOS) or ~/.bashrc (Linux). 3. Run source ~/.zshrc (or source ~/.bashrc) to reload, or open a new terminal.

Problem: Lazarus Cannot Find the Compiler

Symptoms: Lazarus opens but shows an error like "Cannot find Free Pascal Compiler" or "Compiler fpc not found."

Fix: 1. In Lazarus, go to Tools > Options > Environment > Compiler. 2. Set the Compiler Path to the full path of the fpc executable (e.g., C:\FPC\3.2.2\bin\x86_64-win64\fpc.exe on Windows). 3. Click OK and try to compile again.

Problem: "Permission denied" When Running the Compiled Program (macOS/Linux)

Symptoms: Compilation succeeds but ./hello gives "Permission denied."

Fix: The executable does not have the execute permission. Run:

chmod +x hello

Then try ./hello again. Free Pascal usually sets the execute permission automatically, but occasionally file system settings or security software can strip it.

Problem: Antivirus Software Flags the Executable

Symptoms: On Windows, your antivirus quarantines or deletes the compiled .exe immediately after compilation.

Cause: Some antivirus programs flag any newly-created, unsigned executable as suspicious. This is a false positive.

Fix: 1. Add your PascalProjects directory to your antivirus software's exclusion list. 2. Alternatively, use Lazarus (which creates signed debug executables less likely to be flagged).

Problem: "Smart Quotes" Cause Compilation Errors

Symptoms: The compiler reports "Illegal character" on a line that looks correct.

Cause: Your text editor replaced straight quotes (') with typographical "smart quotes" or "curly quotes" (which look like left and right single quotes). Pascal requires straight ASCII quotes.

Fix: In your editor, disable smart quotes / autocorrect. In Notepad on Windows, this is not an issue. In TextEdit on macOS, go to Edit > Substitutions and uncheck Smart Quotes. In VS Code, set "editor.acceptSuggestionOnCommitCharacter": false.

Problem: Lazarus Window Layout Is Broken

Symptoms: Windows are overlapping strangely, the Object Inspector is missing, or the layout looks wrong.

Fix: Go to View > IDE Internals > Reset Window Layout or simply go to Window menu and ensure all windows (Source Editor, Object Inspector, Messages) are checked. You can also delete the Lazarus configuration directory to reset everything to defaults:

  • Windows: C:\Users\YourName\AppData\Local\lazarus\
  • macOS: ~/.lazarus/
  • Linux: ~/.lazarus/

🐛 Debugging Spotlight: When in doubt, the most reliable troubleshooting step is to compile from the command line. If fpc hello.pas works from the terminal but Lazarus cannot compile, the problem is in Lazarus's configuration, not your code or your Free Pascal installation.


🔄 Check Your Understanding: You have now seen the most common problems and their fixes. Take a moment to verify your setup is working: create a new .pas file, compile it with fpc from the command line, and run the resulting executable. Then open the same file in Lazarus and compile it with F9. If both work, your development environment is ready for the rest of this textbook.


2.9 Project Checkpoint: Setting Up PennyWise

Throughout this textbook, we are building PennyWise, a personal finance manager that starts as a simple console program and grows into a full graphical application. Each chapter adds a new capability. In this chapter, our task is modest but important: create the project directory and write the program shell.

Creating the Project Directory

Good project organization starts from the beginning. Create the following directory structure:

PascalProjects/
  PennyWise/
    src/
    data/
    docs/
  • src/ — All Pascal source files go here.
  • data/ — Data files (we will use this when we add file I/O in Chapter 13).
  • docs/ — Documentation and notes.

Windows (PowerShell):

mkdir C:\PascalProjects\PennyWise\src
mkdir C:\PascalProjects\PennyWise\data
mkdir C:\PascalProjects\PennyWise\docs

macOS / Linux:

mkdir -p ~/PascalProjects/PennyWise/{src,data,docs}

Best Practice: Establish a consistent directory structure from the start. As PennyWise grows — and it will grow to include multiple source files, data files, and configuration — you will be glad you did not dump everything into a single folder.

The PennyWise Shell

Create a file called pennywise.pas in the src/ directory:

program PennyWise;
{ PennyWise — Personal Finance Manager
  A progressive project for "Programming with Pascal"

  Version: 0.1 (Chapter 2 — Project Shell)
  This version establishes the program structure.
  Future chapters will add:
    - Variables and expense tracking (Ch 3)
    - User input and formatted output (Ch 4)
    - Decision logic and menus (Ch 5)
    - Loops for continuous operation (Ch 6)
    - Procedures and functions (Ch 7)
    - And much more...
}

uses
  SysUtils;  { For basic system utilities — we'll use more of this later }

begin
  WriteLn('==========================================');
  WriteLn('  PennyWise - Personal Finance Manager');
  WriteLn('  Version 0.1');
  WriteLn('==========================================');
  WriteLn;
  WriteLn('Welcome to PennyWise!');
  WriteLn('This program will help you track your expenses,');
  WriteLn('manage your budget, and take control of your finances.');
  WriteLn;
  WriteLn('Status: Project shell — more features coming soon!');
  WriteLn;
  WriteLn('Compiled with Free Pascal ', {$I %FPCVERSION%});
  WriteLn('Running on ', {$I %FPCTARGETOS%});
  WriteLn;
  WriteLn('Press Enter to exit...');
  ReadLn;
end.

Let us examine the new elements:

  • uses SysUtils; — This is the uses clause. It tells the compiler to include the SysUtils unit, which provides utility functions for string handling, date/time, file operations, and more. We include it now to establish the pattern, even though our shell does not strictly need it yet.

  • **{$I %FPCVERSION%}`** — This is a **compiler macro**. The `{$I %...%} syntax inserts a compiler-defined value. %FPCVERSION% expands to the Free Pascal version string (e.g., '3.2.2'). %FPCTARGETOS% expands to the target operating system (e.g., 'Windows', 'Linux', 'Darwin'). These are Free Pascal extensions, not standard Pascal.

  • ReadLn; — Waits for the user to press Enter. This keeps the terminal window open so you can read the output.

Compile and Run

Navigate to the src/ directory and compile:

cd PascalProjects/PennyWise/src
fpc pennywise.pas

Run the program:

.\pennywise.exe    (Windows)
./pennywise        (macOS/Linux)

You should see the welcome banner with version information. Press Enter to exit.

💡 Intuition Builder: Right now, PennyWise does nothing useful — it just prints a banner and exits. That is exactly right for a project shell. We have established the program header, the uses clause, the begin/end block, and the compilation workflow. Every future chapter will add to this foundation. By Chapter 38, PennyWise will be a full-featured personal finance application with a graphical interface, database storage, and chart generation — and it will have grown organically from this six-line shell.

Rosa Martinelli, our freelance graphic designer character, would appreciate this approach. As a designer, she knows that a blank canvas is not a finished painting — but it is not nothing, either. It is a properly stretched, properly primed surface ready for work. That is what our PennyWise shell is: a properly structured, properly compiling program ready for features.

Tomas Vieira, our college student, would appreciate something else: the compilation macro {$I %FPCVERSION%} that embeds the compiler version directly into the output. In professional software, knowing which version of the compiler built your executable is critical for debugging. The macro is evaluated at compile time — it is baked into the executable, not looked up at runtime. If you compile PennyWise today and run it a year from now, it will still report today's compiler version. This is another small example of the compile-time vs. runtime distinction that runs through everything in Pascal.

Take a moment to experiment with the shell. Try changing the welcome message. Add your own name to the banner. Change the version number to "0.1.1" and recompile. Each change requires recompilation — but each compilation takes less than a second, and each time, you know the compiler has checked your entire program for correctness before producing the new executable.


2.10 Chapter Summary

This chapter transformed your computer from a general-purpose machine into a Pascal development environment. Let us review what you accomplished:

You installed Free Pascal, the open-source compiler that translates Pascal source code into native executables for Windows, macOS, Linux, and many other platforms. You verified the installation by running fpc -v from the command line.

You installed the Lazarus IDE, the visual development environment that provides syntax-highlighting code editing, integrated debugging, project management, and (for future chapters) a visual form designer for building graphical applications.

You wrote, compiled, and ran your first Pascal program — "Hello, World!" — both from the command line and from within Lazarus. You learned the fundamental workflow: write source code in a .pas file, compile with fpc, run the resulting executable.

You understood the compilation pipeline: source code goes through the compiler (which checks syntax, types, and declarations), produces an object file, which the linker combines with the runtime library to produce a standalone executable. This three-stage process is what makes Pascal a compiled language, and it is why Pascal catches entire categories of errors before your program runs.

You learned the structure of a Pascal program: the program header, the optional uses/const/type/var declaration sections, and the begin...end. main block. You saw three comment styles and learned when to use each.

You set up the PennyWise project, creating a directory structure and compiling the program shell that will grow across every chapter in this textbook.

What Is Ahead

In Chapter 3, we will put actual data into our programs. You will learn about Pascal's type system — integers, real numbers, characters, strings, and Booleans — and discover why strong typing, which might feel restrictive at first, is actually one of Pascal's greatest gifts. Rosa will start tracking her freelance expenses with proper variable declarations, and Tomas will discover that the compiler catches mistakes he would have missed in Python.

The foundation is laid. The tools are sharp. Let us build.


Key Terms Introduced in This Chapter

Term Definition
Compiler A program that translates source code into machine code (object code)
Linker A program that combines object files with library code to produce an executable
Executable A standalone binary file that the operating system can run directly
IDE (Integrated Development Environment) A software application combining a code editor, compiler, debugger, and other tools
Source code The human-readable text of a program, written in a programming language
Object file Intermediate compiled output (.o file) that is not yet a complete program
Free Pascal Compiler (fpc) The open-source Pascal compiler; the command-line tool that compiles .pas files
Lazarus The open-source IDE for Free Pascal, modeled on Delphi
PATH An operating system environment variable listing directories where commands are found
Runtime library (RTL) Pre-compiled code providing built-in procedures like WriteLn and ReadLn
Uses clause A Pascal declaration that imports units (library modules) into a program
Program header The program ProgramName; line that names a Pascal program
String literal Text enclosed in single quotes, e.g., 'Hello, World!'
Comment Text in source code ignored by the compiler, written for human readers

📊 By the Numbers: In this chapter, you installed approximately 1 GB of software, wrote three programs (Hello World, Hello Name, PennyWise shell), produced three native executables, and learned the compilation pipeline that every Pascal program follows. The smallest executable (Hello World) is approximately 150-400 KB and depends on nothing but the operating system. The largest software framework on your machine — your web browser — is approximately 500 MB and requires a network connection to be useful. Perspective matters.