Recent

Author Topic: Order of execution of initialization sections  (Read 531 times)

jwdietrich

  • Hero Member
  • *****
  • Posts: 1232
    • formatio reticularis
Order of execution of initialization sections
« on: June 05, 2023, 09:47:36 pm »
According to FPC's documentation of units, "the initialization parts of the units are executed in the order that the compiler loaded the units when compiling a program". But what determines this order? Is it the order, in which the units are listed in the units section of the main program (or the .lpr file, if Lazarus is used)?

In the Lazarus IDE, the units are also listed in the XML-encoded .lps file. Is it also used for determining the order of the initialization section? And, if so, what takes precedence, the units section in the .lpr file or the order in the .lps file?
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 2.2.6 | FPC 3.2.2 | PPC, Intel, ARM | macOS, Windows, Linux

PascalDragon

  • Hero Member
  • *****
  • Posts: 5444
  • Compiler Developer
Re: Order of execution of initialization sections
« Reply #1 on: June 05, 2023, 09:59:16 pm »
According to FPC's documentation of units, "the initialization parts of the units are executed in the order that the compiler loaded the units when compiling a program". But what determines this order? Is it the order, in which the units are listed in the units section of the main program (or the .lpr file, if Lazarus is used)?

The units are essentially initialized in a depth first order. So if you have a program that uses UnitA and UnitB and UnitA uses UnitC then the order will be UnitA, UnitC and UnitB. Essentially don't rely on a specific order as it might change depending on what units you use. What you can rely on however is that if a unit's initialization section is run is that all units used in the interface section are initialized and - assuming there is no cycle - the ones in the implementation section as well.

In the Lazarus IDE, the units are also listed in the XML-encoded .lps file. Is it also used for determining the order of the initialization section? And, if so, what takes precedence, the units section in the .lpr file or the order in the .lps file?

The Lazarus project files (except for the lpr) are irrelevant to what the compiler does.

jwdietrich

  • Hero Member
  • *****
  • Posts: 1232
    • formatio reticularis
Re: Order of execution of initialization sections
« Reply #2 on: June 05, 2023, 10:53:48 pm »
Thanks, @PascalDragon.
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 2.2.6 | FPC 3.2.2 | PPC, Intel, ARM | macOS, Windows, Linux

 

TinyPortal © 2005-2018