Debugging with Lazarus

Lazarus is an IDE (integrated development environment) for Pascal that includes a nice integrated debugger. Even if you normally use another editor to edit your Pascal code, you will probably want to debug your programs in Lazarus sometimes.

To load your Pascal program into Lazarus, do the following:

  1. Start Lazarus.

  2. A bunch of windows will appear. Choose Project → Close Project.

  3. The Project Wizard window will appear. Click Open Project.

  4. In the Open Project File window, change the dropdown in the lower right from "Lazarus project (*.lpi)" to "All files".

  5. In the Open Project File window, navigate to your Pascal source file, select it and click Open.

  6. A window "File has no project" will appear. Click "Create project".

  7. In the "Create a new project" window, choose Simple Program on the left and click OK.

You will see a source editor window showing your program.

You can now run your program in the Lazarus debugger. To do this, choose Run → Run or press F9. You might want to choose View → Debug Windows → Terminal Output, which displays the Console window. This window shows your program's output and also allows you to enter input from the terminal.

If your program fails with a runtime error, Lazarus will show you the line number where that occurred. At that point you can inspect local variables in your program in the Local Variables window, which you can open via the View → Debug Windows menu. You might also want to open the Watches window, which is also available via View → Debug Windows. In this window you can type in the name of any variable to inspect, even a global variable. You can also inspect individual array elements by typing an expression such as 'a[3]'.

You may also want to step through your code to see it execute one line at a time. To do this, launch the program by choosing Run → Step Into (F7) rather than the Run → Run command. That will pause execution on the first line in your main begin/end block. Now you can step one line at a time via the Run → Step Into (F7) and/or Run → Step Over (F8). The difference between these is that if you are currently stopped on a function call, Step Into steps into the function whereas Step Over runs the function to completion and then pauses at the first line after the function returns.

Finally, you can set a breakpoint on any line you like. To do this, place the cursor on that line and then press F5, or click the mouse in the margin to the left of the editing area. You can then choose the Run → Run command to begin or continue execution. When the progam reaches the breakpoint, it will pause execution. At this you can inspect variables and/or step forward in the code from that point.