Search code examples
delphidelphi-7

How to share functions in Delphi?


For example, I have a couple of functions written for my form. Now, I need the exact same functions in another form. So, how can I share them between the two forms? Please, provide a simple example if possible.


Solution

  • Don't put them in your form. Separate them and put them in a common unit, and add that unit to the uses clause where you need access to them.

    Here's a quick example, but you can see many of the Delphi RTL units (for instance, SysUtils) that do this. (You should learn to use the VCL/RTL source and the demo apps that are included in Delphi; they could answer many of the questions you've posted more quickly than waiting for an answer here.)

    SharedFunctions.pas:

    unit 
      SharedFunctions;
    
    interface
    
    uses
      SysUtils;  // Add other units as needed
    
    function DoSomething: string;
    
    implementation
    
    function DoSomething: string;
    begin
      Result := 'Something done';
    end;
    
    end.
    

    UnitA.pas

    unit
      YourMainForm;
    
    uses
      SysUtils;
    
    interface
    
    type
      TMainForm = class(TForm)   
        procedure FormShow(Sender: TObject);
        // other stuff
      end;
    
    implementation
    
    uses
      SharedFunctions;
    
    procedure TMainForm.FormShow(Sender: TObject);
    begin
      ShowMessage(DoSomething());
    end;
    
    end.
    

    In more recent versions of Delphi than Delphi 7, you can create the functions/methods in a record instead:

    unit
      SharedFunctions;
    
    interface
    
    uses
      SysUtils;
    
    type
      TSharedFunctions = record
      public
        class function DoSomething: string;
      end;
    
    implementation
    
    function TSharedFunctions.DoSomething: string;
    begin
      Result := 'Something done';
    end;
    
    end;
    

    UnitB.pas

    unit
      YourMainForm;
    
    uses
      SysUtils;
    
    interface
    
    type
      TMainForm = class(TForm)   
        procedure FormShow(Sender: TObject);
        // other stuff
      end;
    
    implementation
    
    uses
      SharedFunctions;
    
    procedure TMainForm.FormShow(Sender: TObject);
    begin
      ShowMessage(TSharedFunctions.DoSomething());
    end;
    
    end.