Command line parameters and environment variables

From Free Pascal wiki
Jump to navigationJump to search

Overview

When a program is started a user can give command line parameters and setup environment variables. For example the FreePascal compiler gets most of its parameters via command line options:

 fpc -Fudirectory -gh unit1.pas

Command line parameters - the basics

A pascal program can access the parameters via ParamStr and ParamCount. ParamStr(0) is the program path itself. ParamStr(1) is the first parameter. ParamCount is the number of parameters.

<DELPHI> program Project1;

{$mode objfpc}{$H+}

var

 i: Integer;

begin

 writeln('Program: ',ParamStr(0));
 for i:=1 to ParamCount do
   writeln('Param ',i,': ',ParamStr(i));

end. </DELPHI>

For example:

 $ /tmp/project1 -a
 Program: /tmp/project1
 Param 1: -a

Command line parameters - comfortable

A good program should give a help message when invoked with the wrong parameters and it should follow a common way of giving parameters. The unit custapp that comes with FPC provides the TCustomApplication class, which provides functions to easily check and read parameters. Of course you can still access the parameters directly via ParamStr and ParamCount.

Every LCL application uses this automatically. The Application object is a TCustomApplication.

If you want to write a non LCL program, then create in lazarus a new project of type 'Console Application'. This will create a project1.lpr with some nice goodies, that almost all programs need. Go to the DoRun method.

With TCustomApplication you can access parameters by name. For example your program should print a help text when the user gave the common help parameter -h. The -h is a short option. The long form is the --help. To test whether the user called the program with -h or --help you can use <DELPHI> if HasOption('h','help') then begin

 WriteHelp;
 Halt;

end; </DELPHI>

Note: In an LCL form you must prepend Application. in front of HasOption. For example:

<DELPHI> if Application.HasOption('h','help') then begin

 WriteHelp;
 Halt;

end; </DELPHI>


If you only want to support the short option use: <DELPHI> if HasOption('h',) then ... </DELPHI>

If you only want to support the long option use: <DELPHI> if HasOption('help') then ... </DELPHI>