Difference between revisions of "Program/ru"
Line 2: | Line 2: | ||
Понятие '''программа''' означает либо [[Executable program/ru|исполняемая программа]], т.е. самодостаточное и запускаемое [[Application|приложение]], либо часть [[File|файла]] (файлов) с [[Source code|исходным кодом]] на языке [[Pascal]], который может быть скомпилирован и не объявлен в виде [[Unit|модуля]] или [[Library|библиотеки]]. Иногда оно называется главной программой. | Понятие '''программа''' означает либо [[Executable program/ru|исполняемая программа]], т.е. самодостаточное и запускаемое [[Application|приложение]], либо часть [[File|файла]] (файлов) с [[Source code|исходным кодом]] на языке [[Pascal]], который может быть скомпилирован и не объявлен в виде [[Unit|модуля]] или [[Library|библиотеки]]. Иногда оно называется главной программой. | ||
+ | |||
+ | __TOC__ | ||
== Главная программа == | == Главная программа == | ||
Line 17: | Line 19: | ||
Тем временем [[FPC]] ''отбрасывает'' заголовок программы, т.е. первую строку. Имя выходного файла определяется именем файла исходного кода. Однако имя программы ''становится'' зарезервированным [[Identifier|идентификатором]] (за исключением режимов <abbr title="International Organization for Standardization">ISO</abbr> [начиная с [FPC 3.3.1/trunk revision #45757; cf. {{MantisLink|37322}}]). В приведенном выше примере, например. попытка определить константу с именем <syntaxhighlight lang="pascal" inline>hiWorld</syntaxhighlight> вызовет ошибку [[Compile time|времени компиляции]] повторяющегося идентификатора. Имя программы идентифицирует глобальную [[Scope|область]], поэтому его можно использовать для записи полных идентификаторов. | Тем временем [[FPC]] ''отбрасывает'' заголовок программы, т.е. первую строку. Имя выходного файла определяется именем файла исходного кода. Однако имя программы ''становится'' зарезервированным [[Identifier|идентификатором]] (за исключением режимов <abbr title="International Organization for Standardization">ISO</abbr> [начиная с [FPC 3.3.1/trunk revision #45757; cf. {{MantisLink|37322}}]). В приведенном выше примере, например. попытка определить константу с именем <syntaxhighlight lang="pascal" inline>hiWorld</syntaxhighlight> вызовет ошибку [[Compile time|времени компиляции]] повторяющегося идентификатора. Имя программы идентифицирует глобальную [[Scope|область]], поэтому его можно использовать для записи полных идентификаторов. | ||
− | + | Список файловых дескрипторов полностью игнорируется, за исключением [[Mode iso|<syntaxhighlight lang="pascal" inline>{$mode ISO}</syntaxhighlight>]]. [[Text/ru|<syntaxhighlight lang="pascal" inline>Текстовые</syntaxhighlight>]] [[Variable/ru|переменные]] {{Doc|package=RTL|unit=system|identifier=input|text=<syntaxhighlight lang="pascal" inline>input</syntaxhighlight>}}, {{Doc|package=RTL|unit=system|identifier=output|text=<syntaxhighlight lang="pascal" inline>output</syntaxhighlight>}} и {{Doc|package=RTL|unit=system|identifier=stderr|text=<syntaxhighlight lang="pascal" inline>stderr</syntaxhighlight>}} всегда открыты и их имена нельзя изменить в других режимах. (ср.: {{Doc|package=RTL|unit=system|identifier=sysinitstdio|text=<syntaxhighlight lang="pascal" inline>SysInitStdIO</syntaxhighlight>}} всегда вызывается в {{gitlab|tree|FPC|release_3_0_4/rtl/linux/system.pp#L367-L368|<tt>rtl/linux/system.pp</tt>}}) | |
− | |||
− | + | Поэтому с помощью FPC следующий полный пример исходного кода компилируется так же, как и предыдущий пример. | |
<syntaxhighlight lang="pascal"> | <syntaxhighlight lang="pascal"> |
Revision as of 17:42, 29 May 2022
│
Deutsch (de) │
English (en) │
suomi (fi) │
français (fr) │
Bahasa Indonesia (id) │
italiano (it) │
português (pt) │
русский (ru) │
Понятие программа означает либо исполняемая программа, т.е. самодостаточное и запускаемое приложение, либо часть файла (файлов) с исходным кодом на языке Pascal, который может быть скомпилирован и не объявлен в виде модуля или библиотеки. Иногда оно называется главной программой.
Главная программа
program
— это зарезервированное слово, которое представляет файл с исходным кодом классической программы:
program hiWorld(input, output, stdErr);
begin
writeLn('Hi!');
end.
Тем временем FPC отбрасывает заголовок программы, т.е. первую строку. Имя выходного файла определяется именем файла исходного кода. Однако имя программы становится зарезервированным идентификатором (за исключением режимов ISO [начиная с [FPC 3.3.1/trunk revision #45757; cf. Issue #37322]). В приведенном выше примере, например. попытка определить константу с именем hiWorld
вызовет ошибку времени компиляции повторяющегося идентификатора. Имя программы идентифицирует глобальную область, поэтому его можно использовать для записи полных идентификаторов.
Список файловых дескрипторов полностью игнорируется, за исключением {$mode ISO}
. Текстовые
переменные input
, output
и stderr
всегда открыты и их имена нельзя изменить в других режимах. (ср.: SysInitStdIO
всегда вызывается в rtl/linux/system.pp)
Поэтому с помощью FPC следующий полный пример исходного кода компилируется так же, как и предыдущий пример.
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.
- A (depending on used compiler possibly optional) program header.
- There can be at most one
uses
-clause and it has to be at the top of the program right after the program header. - 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.
- A
type
-section comes prior any section that can use types, e.g.var
-sections or routine declarations. - Since
goto
is known as the devil’s tool, alabel
-section, if any, is as close as possible to the statement-frame it is supposed to declare labels for. - Generally you go from general into specifics: For example a
var
-section comes in front of athreadVar
-section. Aconst
-section comes before aresourceString
-section. resourceString
-sections can be either static or global, that means they should appear relatively soon after theuses
-clause.- Direct usage of global variables in routines (or even the mere possibility) is considered as bad style. Instead, declare/define your routines prior any
var
-(like)-section. (beware: play it safe and set{$writeableConst off}
) - Global compiler directives, especially such that allow or restrict what can be written (e.g.
{$goto on}
allows the use ofgoto
) or implicitly add unit dependencies like{$mode objFPC}
should appear soon after the program header.
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
- unit
- library
- program structure in the Object Pascal Introduction series
- § “Beginning” in the Pascal Programming book on Wikibooks.org