Hi,

On Mon, 27 Mar 2023, Jacob Kroon via fpc-pascal wrote:

> As I understand it, in order to translate this to something that FreePascal
> understands, the variable needs to go in a "unit" and be part of its
> interface. Then, pascal sources that needs to reference the variable should
> use this unit. Is this the easiest way forward ?

Probably yes, but there might be an alternative, see below. But as far as
I understand, Unit is a Turbo Pascal concept, so any Pascal programming
dialect that predates it, probably don't understand it.

> I thought maybe I instead could adapt the syntax like:
>
> var
> foobar : integer; external;
>
> but with this I still get undefined references when linking. Using units seems
> ok.

Yes, because all symbols in a Pascal unit are stored as mangled names,
which includes the Unit name. This way you can have "foobar" defined in
two different units, and can still reference them as Unit1.foobar; and
Unit2.foobar;. But of course it will cause linker errors, because the
compiler has no way of knowing the right mangled name. External is
normally used to link against C libraries, which don't use name mangling.

If you want to export a variable without name mangling, you must declare a
public name for it, something like:

var
  foobar: integer; public name '_myfoobar';

Then reference it as:

var
  foobar: integer; external name '_myfoobar';

You might wanna consider this approach, because if units somehow end up
cross-referencing each other, then you might run into difficulties
restructuring the code to use Units. Also, it is possible to
cross-reference units from eachother, but there are some caveats.

With the external way, you only need to change the declarations of
variables, no need to restructure the code, although for long-term
maintenance, that might be still beneficial.

Charlie
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to