Program/ru

This is an old revision of Program/ru, edited by Zoltanleo at . The current revision is 126545.

Понятие программа означает либо исполняемая программа, т.е. самодостаточное и запускаемое приложение, либо часть файла (файлов) с исходным кодом на языке Pascal, который может быть скомпилирован и не объявлен в виде модуля или библиотеки. Иногда оно называется главной программой.

Главная программа

program — это зарезервированное слово, которое представляет файл с исходным кодом классической программы:

program hiWorld(input, output, stdErr);

begin
    writeLn('Hi!');
end.

Тем временем FPC отбрасывает заголовок программы, т.е. первую строку. Имя выходного файла определяется именем файла исходного кода. Однако имя программы становится зарезервированным идентификатором (за исключением режимов ISO [начиная с [FPC 3.3.1/trunk revision #45757; cf. 37322 Issue #37322]). В приведенном выше примере, например. попытка определить константу с именем hiWorld вызовет ошибку времени компиляции повторяющегося идентификатора. Имя программы идентифицирует глобальную область, поэтому его можно использовать для записи полных идентификаторов.

The file descriptor list is completely ignored, except in {$mode ISO}. The text variables input, output and stderr are always opened and their names can not be changed in other modes. (cf.: SysInitStdIO is always called in fpc/source/-/tree/release_3_0_4/rtl/linux/system.pp#L367-L368 rtl/linux/system.pp)

Therefore with FPC the following complete source code example compiles identically as does the previous example.

begin
    writeLn('Hi!');
end.

If the program is syntactically correct, FPC ignores anything that comes after the final end.. The following will compile without problems:

program awesomeProgram(input, output, stdErr);
begin
    writeLn('Awesome!');
end.I thank my mom, my dad, and everyone who supported me in making this program.

This “feature” is primarily used to supply an in-file changelog or copyright notice.

FPC does not support multiple modules in one source code file, like some other compilers did or do. Each module source code has to reside in its own file. However, the restriction that module names have to match file names does not apply to programs. This is due to the fact that programs cannot be included by other modules, thus searching them (via their file name) is not necessary.

Program structure

A program file has to follow a certain structure.

  1. A (depending on used compiler possibly optional) program header.
  2. There can be at most one uses-clause and it has to be at the top of the program right after the program header.
  3. Exactly one block that concludes with an end. (note the period). This block may contain – in contrast to regular blocks – resourcestring section(s).

The exact order and number of various sections after the (optional) uses-clause until final the compound statement begin…end. is free of choice.

However, there are some plausible considerations.

Taking all considerations into account the rough program structure should look like this (except for label and {$goto on} which are only mentioned for the sake of completeness):

program sectionDemo(input, output, stdErr);

// Global compiler directives ----------------------------
{$mode objFPC}
{$goto on}

uses
    sysUtils;

const
    answer = 42;

resourceString
    helloWorld = 'Hello world!';

type
    primaryColor = (red, green, blue);

procedure doSomething(const color: primaryColor);
begin
end;

// M A I N -----------------------------------------------
var
    i: longint;

threadVar
    z: longbool;

label
    42;
begin
end.

[The example consciously ignores the possibility of “typed constants”, sticking rather to traditional concepts than unnecessarily confusing beginners.]

See also