LoginSignup
0
0

More than 5 years have passed since last update.

動作 OS に合わせてコードの分岐を行う

Last updated at Posted at 2016-01-15

コンパイル時点でOS毎に分岐

OS固有のAPIを呼び出したり、OS毎に処理を分岐させたい場合に
実行時にアプリを起動しているOSの種別を取得して処理を分岐する方法もありますが、コンパイル時点で処理を分岐する方法もあります。
コンパイル時に処理を分岐するには、{$ifdef }命令を記載します。
{$ifdef } は、関数内に記載しても良いですし、クラス定義の段階で記載しても良いです。

記載例

  {$ifdef Darwin}
    // ここに Mac OS 向けのコードを記載
  {$else}
  {$ifdef Windows}
    // ここに Windows OS 向けのコードを記載
  {$else}
    // ここに Linux 等、他の OS 向けのコードを記載
  {$endif}
  {$endif}

クラス定義の分岐の例

type
  TTestObject = class(TObject)
  private
  {$ifdef Darwin}
    // ここに Mac OS 向けのコードを記載
  {$else}
  {$ifdef Windows}
    // ここに Windows OS 向けのコードを記載
  {$else}
    // ここに Linux 等、他の OS 向けのコードを記載
  {$endif}
  {$endif}
  end;

関数内の分岐の例

function GetText(): String;
begin
  {$ifdef Darwin}
    // ここに Mac OS 向けのコードを記載
  {$else}
  {$ifdef Windows}
    // ここに Windows OS 向けのコードを記載
  {$else}
    // ここに Linux 等、他の OS 向けのコードを記載
  {$endif}
  {$endif}
end;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0