22 Votes

Lazarus: Detect Operating System (Compiler Switch)

Tip by Delphian | Last update on 2021-04-29 | Created on 2013-05-17

When writing applications for multiple operating systems using Lazarus, it might be necessary to use different code or to include different units at some points depending on the current operating system. Nevertheless, of course, you do not want to adjust the code again and again to the current system you are compiling on. We would like to have a solution to use the same code on all systems, although there are some system depending parts.

So, in this tip, I would like to show you a way of how to show the compiler that a certain code should only apply to a specific system. You can use the compiler directives {$IFDEF}, {$ENDIF} as well as {$ELSE} for this.

First, just have a look at a small example:

{$IFDEF WINDOWS}
   {$IFDEF WIN32}
      showmessage('32 Bit Windows');
   {$ENDIF}

   {$IFDEF WIN64}
      showmessage('64 Bit Windows');
   {$ENDIF} 
{$ELSE}
   showmessage('No Windows.');
{$ENDIF}

In this example, first we are using an IF condition to check whether we are on a Windows system. If so, we look up whether it is a 32 bit or 64 bit Windows and we alert this. If not, we alert a message that it is not Windows.

You can combine the directives as you want and you can use them at the place you want. So, you can not only make code accessible for a specific system, but you can also define or leave out units in the USES clause depending on the system.

List of Operating System Directives

In this table, I have listed the most important directives for each system.

SystemDirective
Alle Windows Systeme{$IFDEF WINDOWS}
Windows 32 Bit{$IFDEF WIN32}
Windows 64 Bit{$IFDEF WIN64}
Windows CE{$IFDEF WINCE}
Linux{$IFDEF LINUX}
Mac OS X{$IFDEF DARWIN}
Classic Macintosh{$IFDEF MAC}
OS2{$IFDEF OS2}
FreeBSD{$IFDEF FREEBSD}
NetBSD{$IFDEF NETBSD}
Amiga{$IFDEF AMIGA}
Atari{$IFDEF ATARI}
PalmOS{$IFDEF PALMOS}

For more directives, please visit Compiler Defines During Compilation on freepascal.org. With those directives, you can for example detect the CPU in use and many other things.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

What is the best Operating System?

Open Voting | 7 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.