Installing Lazarus on macOS/ru

From Lazarus wiki
Jump to navigationJump to search
macOSlogo.png

Эта статья относится только к macOS.

См. также: Multiplatform Programming Guide

Template:Installing Lazarus on MacOS X

Установка Lazarus на Mac не особенно сложна, но очень важно выполнить установку в правильном порядке. Пропуск шагов почти наверняка приведет к плачу Ярославны. Вкратце, вот что вы должны сделать -

  1. Загрузить и установить Xcode.
  2. Установить глобальные инструменты командной строки для Xcode.
  3. Установить Free Pascal Compiler и исходники FPC
  4. Установить Lazarus
  5. Настроить LLDB - поставляемый (и подписанный) Apple отладчик от Lazarus.
Light bulb  Примечание: если вы устанавливаете версии Lazarus до 2.0.0, вам почти наверняка понадобится gdb, см. раздел Legacy.


Установка

В подробных инструкциях предполагается, что на вашем Mac установлена последняя версия macOS, последняя версия Xcode от Apple и последняя версия Lazarus. Внизу страницы, под устаревшей документацией, вы увидите более старую информацию, которая может иметь значение, если вы используете старые компоненты. Вы можете помочь, заменив устаревшую информацию, либо удалив ее, либо, если это может помочь кому-то, работающему с унаследованным проектом, переместить ее в конец страницы.

В общем, речь идет об использовании набора виджетов Carbon и Cocoa. Хотя Carbon все еще можно считать немного более стабильным, на момент выпуска 2.0.0 64-битное Cocoa очень близко [к стабильному] и, безусловно, его следует учитывать. Carbon намеренно (Apple) ограничен 32 битами, и мы знаем, что следующая версия MacOSX, вероятно, не будет его поддерживать.

Шаг 1. Загрузка Xcode.

Вам нужны инструменты Apple Developer, которые являются частью среды разработки Xcode. Они могут быть установлены с оригинальных установочных дисков MacOS или более новой копии, загруженной с Apple Developer Connection (ADC), для которой требуется бесплатная регистрация: ссылка. Загрузите файл Xcode, он окажется в вашем каталоге Downloads в виде zip-файла. На сентябрь 2017 года это Xcode_9_beta_6.xip, около 5Гб. Кликните по нему. Он разархивируется в ваш каталог Downloads. Возможно, вы будете довольны этим, а может и нет. Другие пользователи увидят путь к нему, но не смогут его использовать. И это непорядок. Поэтому я переместил мой [экземпляр] и затем сказал xcode - выбери, куда он был перемещен (в терминале) -

mv Downloads/Xcode-beta.app /Developer/.
sudo xcode-select -s /Developer/Xcode-beta.app/Contents/Developer

Шаг 2. Инструменты командной строки Xcode

Это показано здесь в качестве отдельного шага, потому что на самом деле это отдельный шаг в дополнение к Шагу 1. Не путайте это с внутренними инструментами командной строки Xcode, которые, по словам графического интерфейса Xcode, уже установлены. Lazarus не может использовать эти инструменты внутренней командной строки Xcode, поэтому сделайте следующее (это быстро и легко) -

xcode-select --install

Начиная с macOS Mojave, вам также необходимо установить заголовочные файлы SDK:

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Шаг 3 FPC, исходники FPC

Получите и установите FPC и исходники FPC. Перед установкой Lazarus необходимо установить совместимый fpc (и исходный код), у вас есть несколько вариантов.

Source Forge

Получить версию релиза можно по ссылке https://sourceforge.net/projects/lazarus/files. Эти двоичные установочные комплекты созданы разработчиками FPC/Lazarus и отслеживают формальные выпуски. Так как эти установочные комплекты не одобрены Apple, вам нужно удерживать нажатой клавишу Control, щелкнуть пакет и выбрать Open(Открыть) и подтвердить, что вы хотите установить его от неизвестного разработчика (то есть того, кто не платит Apple откат).

Для получения официальных/более подробных инструкций для FPC перейдите по адресу [1] (прим.перев.: в оригинале битая ссылка)

Вы можете применить простой и быстрый тест fpc на этом этапе: Testing_FPC_installation.

Другие параметры FPC

Вы также можете рассмотреть возможность использования fpcupdeluxe для установки fpc и, возможно, Lazarus, fpcupdeluxe

Кроме того, вы можете использовать fink, менеджер пакетов для macOS для установки fpc. Обратите внимание, что на момент написания (в начале 2019 года) fink предлагает Lazarus 1.8.4, и в целом он согласен с тем, что требуются версии более поздние, чем 2.0.0 (т.е. не выпускаемые), поэтому, вероятно, они не подходят для разработки Cocoa. Дополнительным бонусом fink является простота установки, а также чистое удаление огромного количества других пакетов программного обеспечения с открытым исходным кодом, включая FreePascal crosscompilers для многих процессоров и систем. Выбор для lazarus - Carbon'ный вид lazarus (предпочитаемый большинством), gtk2, Qt4 и Qt5:

$ fink install lazarus-aqua
// или
$ fink install lazarus-gtk2
// или
$ fink install lazarus-qt4
// или
$ fink install lazarus-qt5

Вам будет задан вопрос, устанавливать ли ряд зависимостей, включая компилятор FreePascal, исходные коды lazarus. Просто нажмите Enter и сразу же идите пить кофе. Сборка всех пакетов может занять некоторое время, особенно на старых Mac.

После установки Lazarus можно запустить из папки /Applications/Fink/. Фактические детали fpc и lazarus находятся в подкаталогах /sw

Для любого пакета lazarus от fink эти наборы виджетов поддерживаются для вашей программы в macOS: carbon (Aqua), gtk2, qt4 (Aqua), qt5 (Aqua), nogui, win32, win64 и wince.

Если вы установите fpc из fink, у вас все получится, скачав исходный код Lazarus и скомпилировав его, как описано ниже. Однако, возможно, не стоит смешивать fink fpc с установкой бинарников Lazarus от sourceforge.

Установка Lazarus

На момент написания статьи (начало 2019 года) существует ряд причин, по которым вам может быть лучше использовать еще не выпущенную версию Lazarus, а именно fixes_2_0. Особенности -

  • Вам почти наверняка понадобится Cocoa, скорее всего, следующая версия MacOSX не будет поддерживать 32-битный Carbon.
  • Вы почти наверняка захотите использовать lldb вместо gdb - гораздо проще установить.
  • Cocoa постоянно улучшается, и интерфейс lldb быстро улучшается, начиная с 2.0.0.
  • Fixes_2_0 безопаснее и стабильнее, чем trunk, но получает новые вещи намного быстрее, чем release версия.

Предварительно скомпилированные двоичные файлы, основанные на fixes_2_0, недоступны в SourceForge, но их можно получить из fpcupdeluxe. Но здесь мы обсудим загрузку исходного кода и сборку. Немного медленный изначально, но очень надежный и отличный тест установки вашего компилятора! Вам понадобится svn (он не был предварительно установлен на ранних версиях MacOS, используйте brew или fink для установки).

cd ~
mkdir -p bin/lazarus
cd bin/lazarus
svn checkout https://svn.freepascal.org/svn/lazarus/branches/fixes_2_0 laz_fixes
// ожидаем какое-то время ....
cd laz_fixes
make LCL_PLATFORM=cocoa CPU_TARGET=x86_64 bigide
// ожидаем какое-то время .....
open startlazarus.app --args "--pcp=~/.laz_fixes"
  • Примечание. Я передаю параметр для использования каталога конфигурации, основанного на имени фактического каталога установки. Это делает некоторые сценарии легкими.
  • В настоящее время также вполне возможно (и, возможно, безопаснее на ощупь) создать 32-битную Carbon Lazarus IDE и использовать ее для создания 64-битных приложений Cocoa. Замените упомянутую выше строку на "make LCL_PLATFORM=carbon CPU_TARGET=i386 bigide " и настройте свой проект, как указано в разделе Carbon и Cocoa ниже.

Возможно, вы захотите поместить небольшой скрипт в каталог $HOME/bin и даже указать путь к нему (очень unix!)

#!/bin/bash
LAZDIR="laz_fixes"
cd ~/bin/lazarus/"$LAZDIR"
open ~/bin/lazarus/"$LAZDIR"/lazarus.app --args "--pcp=~/.$LAZDIR"

Настройка отладчика

В версиях Lazarus 1.8.4 и более ранних версиях вам нужно было использовать gdb в качестве отладчика, медленно устанавливать и тяжело подписывать. Начиная с Lazarus 2.0.0 вы можете (и должны) использовать LLDB, отладчик, предоставляемый Apple, подпись [для которого] не требуется.

Предполагая, что вы установили все необходимое и запустили Lazarus, остается только настроить отладчик. Если вы не сделаете этого сейчас, Lazarus попытается использовать GDB и потерпит неудачу.

Сначала нажмите Tools(Инструменты)->Options(Параметры)->Debugger(Отладчик). В правом верхнем углу открытого окна есть надпись "Debugger type and path"(Тип и путь отладчика), вы должны задать оба [значения]. Выберите "LLDB debugger (with fpdebug) (Beta)"(Отладчик LLDB (с помощью fpdebug) (Beta)).

Set Debugger.png

Если его нет в списке выбора, см. ниже (Установка LazDebuggerFpLLdb). Обратите внимание, что изображение выше имеет путь к LLDB, который может отличаться от вашего, в зависимости от того, где были установлены инструменты XCode, в моем случае /Library. Сохраните эти настройки, и теперь вы можете попытаться скомпилировать практически пустую программу, которую Lazarus любезно предоставил для вас (щелкните маленький зеленый треугольник в верхнем левом углу).

Далее вы видите загадочный вопрос, см. изображение ниже. Выберите "Debug Format"(формат отладки) из предложенных -

Set Dwarf.png

Martin_fr (человек, который дал нам этот интерфейс между Lazarus и LLDB) предлагает вам использовать "dwarf3". Затем вам нужно ввести свой пароль: MacOSX хитроумна, потому что одно приложение мешает другому. В этом случае это хорошо!

Дополнительная информация по использованию LLDB

В этой ветке форума появляется много информации об использовании LLDB. Вот еще несколько самоцветов от Martin_fr:

В случае непредвиденных проблем стоит попробовать "dwarf with sets" взамен используемому "dwarf3".

The "debug info" setting only affects the units directly in your project. However units in packages may have debug info too. This can be

  • set per package
  • for many, but not all packages in menu Tools > Configure build Lazarus
  • project settings > Additions and Overrides

If you change settings for package, you may as well check into which package you expect to step. Package you do not step into, do not need debug info. If you use a type from a package (such as TForm from LCL) it is enough that your unit (in which you declare the variable / must declare and use a variable to include the type) has debug info. Reducing the amount of packages with debug info (including those that default to have debug info), can shorten the debuggers start-up time.

Also it may be worth comparing (its not been tested) the debuggers start up time for the same settings, only changing the checkbox "use external debug info". This needs to be only set in your project. If set in your project it will affect all packages. (If set in a package it will do nothing / at least should...)

Installing LazDebuggerFpLLdb"

If you installed from source and used the bigide parameter to make, then the correct debugger will be installed, as a package, and ready to go. If, however, you installed in another way, it may, or may not be there. From the main IDE screen, click Packages->Install/UninstallPackages. Show is two lists of packages, the list on the left is installed, the list on the right is available to install. Look for LazDebuggerFpLldb (exactly that, there are some similar named but less suitable packages). If its on the right hand side, click it, press "Install Selection" and then "Save and rebuild IDE". This will take a little time, the IDE will shutdown and restart and all should be well. Now jump back up the page and continue configuring the debugger.

Compatibility

Not every combination of Lazarus and Free Pascal is compatible with every installation of macOS. Please refer to the following table in order to find the correct version for your development environment:

Lazarus Compatibility Matrix
Lazarus 1.8.x Lazarus 2.0.y Lazarus 2.0.8 Lazarus 2.0.10 Lazarus 2.0.12 Lazarus 2.2.y
FPC 3.0.4 FPC 3.2.0 FPC 3.2.2
PPC processors
Mac OS X 10.4 (Tiger) Incompatible Incompatible Incompatible Incompatible Incompatible Incompatible Incompatible
Mac OS X 10.5 (Leopard) Not tested Not tested Incompatible Incompatible Incompatible Incompatible Incompatible
Intel processors
Mac OS X 10.4 (Tiger) Incompatible Incompatible Incompatible Incompatible Incompatible Incompatible Incompatible
Mac OS X 10.5 (Leopard) Not tested Compatible^ Not tested Compatible^** Not tested Not tested Not tested
Mac OS X 10.6 (Snow Leopard) Compatible Compatible^^ Not tested Not tested Not tested Not tested Not tested
Mac OS X 10.7 (Lion) Compatible Not tested Not tested Not tested Not tested Not tested Not tested
OS X 10.8 (Mountain Lion) Compatible^^ Compatible Compatible**# Compatible**# Compatible**# Compatible# Compatible
OS X 10.9 (Mavericks) Compatible^^ Compatible Compatible** Compatible** Not tested Not tested Not tested
OS X 10.10 (Yosemite) Compatible^^ Compatible Compatible** Compatible** Not tested Not tested Not tested
OS X 10.11 (El Capitan) Compatible^^ Compatible Compatible*** Compatible Compatible Compatible Comptaible
macOS 10.12 (Sierra) Compatible^^ Compatible Compatible*** Compatible Compatible Compatible Compatible
macOS 10.13 (High Sierra) Not tested Compatible Compatible*** Compatible Compatible Compatible Comptaible
macOS 10.14 (Mojave) Not tested Compatible Compatible*** Compatible Compatible Compatible Compatible
macOS 10.15 (Catalina) Not tested Compatible Compatible*** Compatible Compatible Compatible Compatible
macOS 11 (Big Sur) Not tested Compatible Compatible*** Compatible Compatible Compatible Compatible
macOS 12 (Monterey) Not tested Not tested Not tested Not tested Not tested Not tested Compatible
macOS 13 (Ventura) Not tested Not tested Not tested Not tested Not tested Not tested Compatible
macOS 14 (Sonoma) Not tested Not tested Not tested Not tested Not tested Not tested Compatible
Apple Silicon M series processors
macOS 11 (Big Sur) Not tested Not tested Not tested Compatible†† Compatible†† Compatible††† Compatible*
macOS 12 (Monterey) Not tested Not tested Not tested Compatible†† Compatible†† Compatible††† Compatible*
macOS 13 (Ventura) Not tested Not tested Not tested Compatible†† Compatible†† Compatible††† Compatible*
macOS 14 (Sonoma) Not tested Not tested Not tested Compatible†† Compatible†† Compatible††† Compatible*

x = 0, 2 or 4; y = 0, 2, 4 or 6

^ Carbon interface compiles - Cocoa does not.

^^ Restrictions apply to debugging with gdb.

* Lazarus 2.2.0 installs universal binaries for FPC 3.2.2, but an Intel Lazarus IDE binary which you can use or recompile the IDE from within itself for a native aarch64 version.

** See Installing Lazarus 2.0.8, 2.0.10 with FPC 3.2.0 for macOS 10.10 and earlier for instructions.

*** See Installing Lazarus 2.0.8 with FPC 3.2.0 for macOS 10.11+ for instructions.

# Cannot run without debugging in the IDE. Can run compiled application outside of the IDE. See Issue #37324. Choose the gdb debugger, change timeout option to false or click through five "timeout" dialogs to run with debugging in the IDE.

Cannot "run without debugging" in the IDE. Can run compiled application outside of the IDE. See Lazarus IDE - Unable to "run without debugging" for workaround. See Issue #36780.

†† You need to compile a native aarch64 version of FPC 3.3.1 (trunk) and Lazarus 2.0.12 from source to support an Apple Silicon M series processor. Refer to these instructions for FPC and these instructions for the Lazarus IDE.

††† After installing FPC 3.2.2, you need to compile a native aarch64 version of Lazarus from source to support an Apple Silicon M series processor. Refer to these instructions for compiling the Lazarus IDE.

See the legacy version of this compatibility matrix for recommended installs on very old versions of macOS.

Carbon и Cocoa

At present (early 2019) Lazarus using Cocoa will meet many users needs. Carbon work pretty much as expected but you are advised to try Cocoa first, especially considering that Apple has indicated releases after Mojave will not support 32bit Carbon. Alternatives include QT and GTK2+, both requiring additional libraries and GTK2+ on the Mac appears to get little attention these days. QT on the Mac does have some strong supporters on the forum.

However, we should assume, Cocoa is the future on Mac. It is possible to build an all Cocoa version of Lazarus with release 2.0.0 and later. It is also possible to make a Carbon install of Lazarus and use that to generate Cocoa 64bit binaries. In a Carbon IDE, you need to set the Target to the 64bit processor and select the Cocoa Widget set:

  • Open your project with Lazarus and click Project/ProjectOptions
  • In the "Config and Target" panel set the "Target CPU family" to be "x86_64"
  • In the "Additions and Overrides" panel click on "Set LCLWidgetType" pulldown and set the value to "Cocoa"
  • In the past, for some reason Lazarus kept setting the compiler to "/usr/local/bin/ppc386" - which results in 32 bit apps. Make sure under Tools->Options that "Compiler Executable" is set to "/usr/local/bin/fpc" to get 64 bit apps.
  • Now compile your project - and please feed back any problems you experience.

Download the sources via svn

The sources are kept in a version control system called subversion or short svn:

  • 10.5 and higher already contains svn clients. Users of earlier versions must install SVN for macOS. A good package is provided by Martin Ott. You can also use fink. SVN clients with GUI (graphical user interface) are available from Versiontracker. A quite handy client, which integrates in Finder, is SCPlugin.

Create a directory, where you would like to put the sources. You don't need to be root to do this. Any normal user can do this. First create a directory for fpc

(e.g. /Users/username/freepascal)

then open a terminal and do the following:

[]$ svn co http://svn.freepascal.org/svn/fpc/trunk fpc

This will create a directory called 'fpc', which can be later used in the IDE. Hint: To download/update the latest changes you can simply do

[]$ cd /Users/username/freepascal/fpc
[]$ svn up

Building fpc

[]$ make clean all
[]$ sudo make install

Then download lazarus

[]$ svn co http://svn.freepascal.org/svn/lazarus/trunk lazarus

This will create a directory called 'lazarus'. To update the latest changes:

[]$ cd /Users/username/freepascal/lazarus
[]$ svn up

Building lazarus

[]$ make clean all

Then start lazarus either via command line or by double click in the finder:

 open lazarus.app

Download stable sources

Source code of stable versions is available in the Lazarus Zip - GZip archives. This is e.g. an option for users, who want to run the latest official Lazarus versions on "unsupported" machines, e.g. PPC-based Macs. Provided that you have installed the latest stable FPC version together with sources, it is sufficient to download and unpack the zip archive. Move it to the desired location (e.g. your /Developer folder), open a terminal window and change the shell's path to this folder (the easiest way to do this is to type "cd " and then to drag the icon of the freshly unpacked Lazarus folder to the position after this command in the Terminal window). If necessary enter <return> and then

[]$ make clean bigide

and <return> again. Subsequently, FreePascal will use the makefile in this folder to build the Lazarus IDE. This may take a few minutes, but the process is fully automated. Therefore, you might want to look for a cup of coffee, while FPC is working. If the compiler is ready it prints the number of processed lines and the required time to the shell's output.

The last step is to right-klick on the Lazarus bundle icon and to select "Show Package Contents" from the context menu. Then drag the executable "lazarus" to the folder "Contents/MacOS" of the bundle. That's it.

Legacy Information

Install gdb

As of the Lazarus 2.0.0 release this is entirely optional. The IDE now supports LLDB directly. See http://forum.lazarus-ide.org/index.php/topic,42869.0.html and http://wiki.lazarus.freepascal.org/Lazarus_2.0.0_release_notes#LLDB_based_Debugger_.28New.29

Getting gdb to run can be a bit tedious but is worthwhile in the end if using Lazarus < V2.0 or have some specific requirement for gdb. You probably don't !

This step should be done after installing XCode and before installing FPC/Lazarus.

  1. Install fink or brew and use them to install gdb- http://wiki.freepascal.org/GDB_on_OS_X_Mavericks_and_Xcode_5
  2. Self sign the gdb binary using tools already on your Mac - https://sourceware.org/gdb/wiki/BuildingOnDarwin This is the tedious part. The instructions are clear except, perhaps they could have mentioned that after you have set the Keychain to ’System’ you need click ‘Create’ and ‘Done’ on the next screen. Then go and find the cert in your overall list of certs to do the next instruction “using the contextual menu…”. Don’t worry about step “2.1.4 Disable starting the debuggee…”, we’ll address that once Lazarus itself is installed and working.
  3. Once Lazarus is installed and fired up, tell it how it should start gdb, that is step 5.

Note that as of April 2018, there may be issues with newest gdb and High Sierra. https://forum.lazarus.freepascal.org/index.php/topic,40874.0.html According to https://stackoverflow.com/questions/49001329/gdb-doesnt-work-on-macos-high-sierra-10-13-3, gdb 8.1 does not work on High Sierra, but 8.0.1 does.

Part 2 of gdb install, Tell Lazarus about starting gdb

Again, this step is not necessary with Lazarus V2.0 and Later. See http://wiki.lazarus.freepascal.org/Lazarus_2.0.0_release_notes#LLDB_based_Debugger_.28New.29 If you do install (and use) gdb, you must tell Lazarus about how to call gdb. Obviously, this step happens after Lazarus is installed.

OK, now you should be able to start Lazarus, it should display the various parts and paths it needs (including gdb) in the little opening screen. You will get an alert there if you chose to not use a debugger. Proceed to the IDE and we now need to tell Lazarus to tell gdb to not open a shell, as noted by a number of Forum people (http://forum.lazarus.freepascal.org/index.php/topic,37310.0.html). Within Lazarus, click Tools->Options->Debugger->General In the “Debugger specific Options” there is a field labeled Debugger_Startup_Options. Type in "--eval-command=set startup-with-shell off" (including the inverted commas) AND press the return key, click OK. Note you cannot copy and paste into this box (##$!). See screen shot.

Debug Startup Options 01.png

Xcode Compatability

Information relating to older versions of FPC, Lazarus and Apple Developer Tools

Compatibility with Xcode 5.0 and newer versions (Mac OS X 10.8, 10.9, 10.10 and 10.11)

Like Xcode 4.3+, Xcode 5 and subsequent versions no longer install the command line tools by default. These are required by FPC/Lazarus, however. Unlike in Xcode 4 the installation option is no longer accessible in Xcode 5 via the Downloads tab. Additionally, the "Locations" tab of the preferences dialog may be confusing, as it mentions that the command line tools are installed:

Default location of command line tools in Xcode 5. Installation of command line tools with the xcode-select command part 1... ...and part 2.

The first dialog box shows that by default the command line tools are only installed inside the Xcode.app bundle itself. To install them globally, as required by FPC/Lazarus, execute the following terminal command:

xcode-select --install

Depending from your Xcode version alternative steps to install the command line developer tools may be to download them directly in the Xcode preferences window (see screenshots above) or to download them from developer.apple.com (please take care to install the command line tools that are correct exactly for your Xcode version).

Xcode 4.3+ compatibility (Mac OS X 10.7/10.8)

Xcode 4.3 and later no longer install the command line tools by default. These are required by FPC/Lazarus.

To install them manually, open Xcode, go to Preferences, select "Downloads;" and install the "Command Line Tools". Afterwards, FPC will install and function correctly.

install command line tools 1.png install command line tools 2.png install command line tools 3.png


It will be necessary to reinstall the command line tools after each upgrade of Xcode (especially when it's a new major version, the installer may delete the old copies of the command line tools), and also after switching to a new major version of the system software (idem). You may also download the command line tools from Apple Developer.

Xcode 3.2.x compatibility (Mac OS X 10.6)

FPC 2.6.0: there is an issue when compiling dynamic libraries with FPC under Mac OS X 10.6 due to a bug in the Xcode 3.2.x linker. This bug has been fixed in Xcode 4. You can work around the bug in Xcode 3.2.x by using the -k-no_order_inits command line parameter when compiling a dynamic library.

Xcode 3.1.x compatibility (Mac OS X 10.5)

Most versions of Lazarus and FPC are compatible with Xcode 3.1 (see the compatibility matrix for detailed reference). The Xcode integration kit is provided as an optional install to allow for developing with Free Pascal directly from Xcode. It is not required for development with Lazarus, however.

Xcode 2.x compatibility (Mac OS X 10.4)

Most versions of Lazarus and FPC are compatible with Xcode 2.3 or newer (see the compatibility matrix for detailled reference). The Xcode integration kit is provided as an optional install to allow for developing with Free Pascal directly from Xcode. It is not required for development with Lazarus, however. Xcode 2.0 was compatible with Lazarus 0.9.x, but it is no longer supported by newer versions of the Lazarus IDE.

Install Packages / Released version

Installation from disk images

Download the three disk images (.dmg files) for fpc, fpcsrc and lazarus from either of the following links:

Open up each disk image and install in this order:

  1. fpc
  2. fpcsrc
  3. Lazarus

After installation the Lazarus application can be found in /Developer/lazarus/, the FPC source files in /usr/local/share/fpcsrc.

If you receive a "Can't find unit Interfaces used by Project1" error on trying to compile a blank form, check the following settings in Lazarus (should be set by default):

Environment Options

  Lazarus directory: /Developer/lazarus
  Compiler path: /usr/local/bin/ppc386 (PowerPC Macs: /usr/local/bin/ppcppc)
  FPC Source: /usr/local/share/fpcsrc

Project | Options

  All paths blank
  LCL Widget Type: default (Carbon beta)

Project | Inspector

  Required Packages
     LCL

Note - different versions of Lazarus depend on particular versions of the FreePascal compiler and will not work with other versions.

Another common problem is that the versions of fpc and fpcsrc are different.

This is the easiest way to install Lazarus on Mac OS X.

Install from Source / Development version

You need the latest stable released FPC installed in order to compile the development version.

Download and install a compiler

Download and install the FPC package: https://sourceforge.net/project/showfiles.php?group_id=89339

There are two development versions of the compiler: 2.6.x is stable version without new features - only bug fixes. The unstable version 2.7.x comes with lots of new features but sometimes also with bugs. Best is to download and install fpc 2.6.x. Some daily snapshots can be found here. Keep in mind that these are daily snapshots and that you can have bad luck and get a buggy version. The probability is about 1:30. So if the version is buggy try another day or use the released packages instead.

Uninstalling Lazarus and Free Pascal

Installed using fink

The complete uninstall of all fpc and lazarus packages is done with:

fink purge --recursive fpc-config

If you want to preserve changes to the preference file /sw/etc/fpc.cfg, do:

fink remove --recursive fpc-config

For the removal of the Lazarus preference folder and files in your home directory, see below ( Lazarus preference folder).

Installed from disk images or sources

Normally you uninstall an application on OS X simply by dragging it from the Applications folder to the trash. But because Lazarus and Free Pascal are development tools, they're installed in several folders that you don't normally see in Finder.

You can copy and save the commands below to file uninstallLaz.sh and run it if you need to uninstall Lazarus and Free Pascal. You can usually install newer versions of Lazarus and Free Pascal over older versions, but as with most software it's not a bad idea to clean out everything before you install a newer version. This list of commands should also give you a sense of where the various pieces of Lazarus and Free Pascal are located.

bin=/usr/local/bin
share=/usr/local/share
lib=/usr/local/lib
receipts=/Library/Receipts
private=/private/etc

rm -fv $bin/ppcppc
rm -fv $bin/ppc386
rm -fv $bin/bin2obj
rm -fv $bin/data2inc
rm -fv $bin/delp
rm -fv $bin/fd2pascal
rm -fv $bin/fpc
rm -fv $bin/fpcmake
rm -fv $bin/fpcmkcfg
rm -fv $bin/fpcsubst
rm -fv $bin/fpdoc
rm -fv $bin/fprcp
rm -fv $bin/h2pas
rm -fv $bin/h2paspp
rm -fv $bin/makeskel
rm -fv $bin/mkxmlrpc
rm -fv $bin/plex
rm -fv $bin/postw32
rm -fv $bin/ppdep
rm -fv $bin/ppudump
rm -fv $bin/ppufiles
rm -fv $bin/ppumove
rm -fv $bin/ptop
rm -fv $bin/pyacc
rm -fv $bin/rstconv
rm -fv $bin/unitdiff
rm -r $private/lazarus
rm -r $bin/lazarus
rm -r $share/lazarus
rm -r $share/fpcsrc
rm -r $share/doc/fpc-2.2.2
rm -r $share/examples/fpc-2.2.2

rm -r $lib/fpc

rm -r $receipts/lazarus-*.pkg
rm -r $receipts/fpcsrc-*.pkg
rm -r $receipts/fpc-*.pkg

rm -fv /etc/fpc.cfg

Note that this assumes you have version 2.2.2 snapshot of Free Pascal installed. If you have a different version, change the two relevant commands to specify your version.

To run this script, change to the directory where it's stored and enter:

chmod +x uninstallLaz.sh
sudo ./uninstallLaz.sh

Then enter your password when prompted.

Lazarus preference folder .lazarus in the home directory

Note: Lazarus also creates a .lazarus folder in your home directory where it stores environment settings and a list of recently opened projects and files. You can leave this folder alone if you want the new version of Lazarus you're installing to use your old settings. macOS normally doesn't show files or folders whose names start with a dot (.). To see this folder and its contents, enter the following in a terminal window:

cd ~/
ls -al
cd .lazarus
ls

To remove it, execute the following commands:

cd ~/
rm -rv .lazarus

Known issues

  • FPC 2.4.4 has a bug. You can not compile the IDE with the range check flag -Cr.
  • On OS X 10.4 you have to manually uninstall any previous version before installing a new dmg. Delete the following files and folders:
    • /Developer/lazarus
    • /Library/Receipts/lazarus.pkg
    • /etc/lazarus
    • /usr/local/bin/lazbuild

See Also

Other Interfaces

Platform specific Tips

Mac How To Articles

  • Mac How - Если у вас возникли проблемы в решении некоторых серьезных проблем (прим.перев.: поправил ссылку на похожую, поскольку в оригинальной статье ссылка заблокирована спам-фильтром и ведет на левый сайт).

Interfaces Development Articles