0

I never know what is the reason of where and why I should put uses clause place.

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs; // why put on top ?

type
  TForm2 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

uses  System.Math, System.IOUtils, System.WideStrUtils; // why put here ?

procedure TForm2.FormCreate(Sender: TObject);
begin
  //
end;

end.

Also, what is the first priority of uses unit does? Why winapi.windows always on first place, what happens if not in first place?

Dheeraj Joshi
  • 1,522
  • 14
  • 23
Bianca
  • 973
  • 2
  • 14
  • 33
  • 4
    Documentation might shed some light: [Unit References and the Uses Clause](http://docwiki.embarcadero.com/RADStudio/en/Programs_and_Units_(Delphi)#Unit_References_and_the_Uses_Clause). There is also a similar question: [Adding a unit to the Interface uses clause rather than the Implementation uses clause](https://stackoverflow.com/q/528472/576719) – LU RD Feb 15 '18 at 06:35
  • 1
    If you would put `Vcl.Controls`in the second uses then all components that are declared in that unit will be unknown in your TForm2 declaration. You could not have a TButton in TForm2 anymore for example. So any units where you only need declarations from in your code, and not in your TForm2 declaration, you could put in the second uses – GuidoG Feb 15 '18 at 14:49

1 Answers1

9

Help tells us :

The order in which units appear in the uses clause determines the order of their initialization and affects the way identifiers are located by the compiler. If two units declare a variable, constant, type, procedure, or function with the same name, the compiler uses the one from the unit listed last in the uses clause.

As example for the second reason - try to place Graphics before Windows unit and use TBitmap

MBo
  • 77,366
  • 5
  • 53
  • 86