Your first cli-fp program
Documentation home · How do I...? · Command shapes · Options
Start with one root command when your program has one default action. The complete program below is also the repository's QuickStartDemo, which is compiled by the Windows and Linux example smoke checks.
The program follows the normal v1.4.x ownership model: THelloCommand descends from TBaseCommand, Main is its instance and owns --name, and App is the ICLIApplication that parses the invocation and calls Main.Execute.
program QuickStartDemo;
{$mode objfpc}{$H+}{$J-}
uses
CLI.Interfaces, CLI.Application, CLI.Command;
type
THelloCommand = class(TBaseCommand)
public
function Execute: Integer; override;
end;
function THelloCommand.Execute: Integer;
var
PersonName: string;
begin
if not GetParameterValue('--name', PersonName) then
PersonName := 'World';
WriteLn('Hello, ', PersonName, '!');
Result := 0;
end;
var
App: ICLIApplication;
Main: THelloCommand;
begin
Main := THelloCommand.Create('', 'Print a greeting');
Main.AddStringParameter('-n', '--name', 'Name to greet', False, 'World');
App := CreateCLIApplication('hello', '1.0.0', Main);
Halt(App.Execute);
end.
Compile from a clone of this repository:
fpc -Fu./src ./examples/QuickStartDemo/QuickStartDemo.lpr
./examples/QuickStartDemo/QuickStartDemo --name Ada
fpc "-Fu.\src" .\examples\QuickStartDemo\QuickStartDemo.lpr
.\examples\QuickStartDemo\QuickStartDemo.exe --name Ada
Both commands print Hello, Ada!. Run --help to see generated usage and the option description.
What the program does
TBaseCommandsupplies parameter registration and lookup.- An empty command name creates the root (default) action, so users run
hello --name Ada, nothello greet --name Ada. CreateCLIApplicationparses arguments, validates registered options, shows help, and returns the exit code fromExecute.
Next, choose whether your application should remain a root command or grow into named or nested commands. For common variations, go to How do I...?.