freepascal

How to make {$DEFINE xxx} visible to other units in FreePascal?


I made a PlatformDetection.pas source file with some DEFINE to detect the platform:

{$IF DEFINED(CPUARM)}
  {$DEFINE ARM}
{$ELSE}
  {$IF DEFINED(i386) or DEFINED(cpui386) or DEFINED(cpux86_64)}
    {$DEFINE INTEL}
  {$IFEND}
{$ENDIF}

{$IFDEF INTEL}
  // Code here is compile, as expected with my processor
{$ENDIF} 

This "seems" to work in functions inside that file. However, when used in other units, those symbols seems not defined:

uses PlatformDetection;

...

{$IFDEF INTEL}
   // Code here not compiled, even through this same line work when used inside PlatformDetection.pas.
{$ENDIF}

My question is: How to make DEFINE symbols visible in other units?


Solution

  • {$DEFINE} symbols are not visible across unit boundaries. Only symbols that are defined globally in the project settings, or via the command-line -d option, are visible across unit bounaries.

    But, what you can do instead is put the {$DEFINE} directives in a .inc file, and then use a {$I} directive in any unit that needs to see the symbols, eg:

    PlatformDetection.inc:

    {$IF DEFINED(CPUARM)}
      {$DEFINE ARM}
    {$ELSE}
      {$IF DEFINED(i386) or DEFINED(cpui386) or DEFINED(cpux86_64)}
        {$DEFINE INTEL}
      {$IFEND}
    {$ENDIF}
    

    SomeUnit.pas:

    {$I 'PlatformDetection.inc'}
    
    ...
    
    {$IFDEF INTEL}
      // Code here is compiled, as expected with my processor
    {$ENDIF}