Forum > Editor

Detect if unit is used in interface or implementation only

<< < (2/2)

PascalDragon:

--- Quote from: Joanna on July 29, 2024, 01:39:24 am ---So here is a question, if unit1 uses classes and unit2 uses unit1 and also uses classes , can unit2 use the classes unit declared in unit1 instead of having classes unit in its own uses section? Logically it should word but if it does it’s bad to not have everything that unit2 uses visible at top of unit.

--- End quote ---

Every unit must have any unit it directly(*) accesses in one of its uses-sections. That's the whole point of the unit concept, so that it's clear what a unit uses (for both the user and the compiler).

(*) There are some exceptions, e.g. if you use a type only indirectly like here (note: this is a stupid example that has a memory leak, it's only to highlight the indirect use):

Unit utest.pp:


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---unit utest; {$mode objfpc}{$H+} interface uses  Classes; function Test: TStrings; implementation function Test: TStrings;begin  Result := TStringList.Create;  Result.Add('Hello World');end; end.
Program ttest.pp:


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---program ttest; {$mode objfpc}{$H+} uses  utest; begin  Writeln(Test.Text);end.
As you can see the compiler knows about the methods of TStrings inside ttest despite not having Classes in the uses-clause. If you'd want to store the return value of Test however you'd have to declare a suitable variable and thus declare the Classes unit in the uses-clause.

cdbc:
Hi
@Joanna: If need be, you can /forward/ a type, by aliasing it in the unit, e.g.:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---unit utest; {$mode objfpc}{$H+} interface uses  Classes;//////////////// here /////////type    TStrings = classes.TStrings; // alias/////////////// function Test: TStrings; implementation...Regards Benny

Joanna from IRC:
That’s an idea  :)

Navigation

[0] Message Index

[*] Previous page

Go to full version