Installing Lazarus on macOS/ru

From Lazarus wiki
Jump to navigationJump to search

English (en) español (es) 한국어 (ko) русский (ru)

macOSlogo.png

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

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


Установка 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 (необязательно).

Xcode — это загрузка 12ГБ архива, которая займет после распаковки 16ГБ дискового пространства. Имеет смысл заружать и устанавливать полную среду разработки Xcode, только если вам нужны:

  • SDK для iOS, iPadOS, watchOS и tvOS; или
  • для проверки и загрузки приложений в Mac App Store; или
  • нотариально заверять приложения для распространения за пределами Mac App Store.

Xcode 11.3.1 для использования в macOS 10.14 Mojave теперь необходимо устанавливать, загрузив его из Apple Developer Connection (ADC), для чего требуется бесплатная регистрация. Xcode 12.4.x для использования в macOS 10.15 Catalina и более поздних версиях можно установить из магазина приложений Mac App store. Обратите внимание, что вы должны сначала переместить все старые версии Xcode из папки «Приложения» в корзину или переименовать приложение Xcode (например, Xcode.app в Xcode_1014.app). Затем вы можете выбрать, какую версию Xcode использовать с помощью утилиты командной строки xcode-select. Откройте Applications > Utilities > Terminal (Приложения > Инструменты > Терминал) и введите man xcode-select для показа страниц руководства по этой утилите.

Старые системы:

Инструменты разработчика Xcode можно установить с исходных установочных дисков macOS или более новой копии, загруженной из Apple Developer Connection (ADC), для чего требуется бесплатная регистрация. Загрузите файл Xcode, он окажется в вашем каталоге загрузок в виде zip-файла. Нажмите на нее. Он разархивируется в каталог Downloads(Загрузки). Вам может повезти, а может быть и нет. Другие пользователи увидят путь к нему, но не смогут его использовать. А это - непорядок. Чтобы исправить это недоразумение, я переместил свой, а затем указал xcode-select, куда он был перемещен (в терминале) -

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

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

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

Сделайте следующее, это быстро и легко для всех версий macOS до Catalina 10.15 включительно:

sudo xcode-select --install
sudo xcodebuild -license accept


Для Big Sur 11.x и более поздних версий вам нужно ввести только первую из двух приведенных выше команд, если вы также не установили полный пакет Xcode. Если вы установили только инструменты командной строки, вам не следует вводить команду xcodebuild.

Если у вас возникли проблемы с установкой инструментов командной строки с использованием этого метода командной строки (например, программа установки зависает при «поиске программного обеспечения»), вы также можете загрузить и установить пакет инструментов командной строки, зайдя на Apple Developer Site и загрузив и установив образ диска Command Line Tools for Xcode.

Шаг 3 Бинарные файлы FPC и исходный код FPC

Light bulb  Примечание: Для установки Apple Silicon/AArch64/M1, если вы устанавливаете FPC 3.2.2 (Lazarus 2.2RCx или 2.2.0 или более поздние версии), вам не нужно компилировать собственную версию FPC для Apple Silicon, поскольку FPC 3.2.2 для macOS универсальный двоичный файл, содержащий исполняемые файлы Intel и aarch64. Если вы устанавливаете более раннюю, чем 3.2.2, версию FPC, обратитесь к этим инструкциям для создания собственного компилятора Apple Silicon Free Pascal после установки 64-разрядного двоичного файла Intel и исходных пакетов для FPC.

Загрузите и установите официальный пакет двоичных файлов FPC и отдельный пакет исходного кода FPC из области файлов Lazarus IDE.

Когда вы доберетесь до области файлов Lazarus IDE:

  1. Выберите правильную версию вашей операционной системы. Подавляющее большинство пользователей Mac теперь должны выбирать 64-битные пакеты в каталоге Lazarus macOS x86-64. Каждый компьютер Mac с конца 2006 года поддерживает 64-разрядную версию. Тот факт, что Apple полностью отказалась от 32-битной поддержки в macOS 10.15 Catalina (выпущенной в октябре 2019 года), является еще одной причиной для выбора 64-битных пакетов.
  2. Выберите версию Lazarus, которую вы хотите установить, и вам будут представлены два бинарных и исходных пакета FPC для загрузки.

Эти установочные пакеты создаются разработчиками FPC/Lazarus и отслеживают официальные выпуски. Поскольку эти установочные пакеты не одобрены Apple, вам нужно, удерживая нажатой клавишу Control, щелкнуть пакет, выбрать «Открыть» и подтвердить, что вы хотите установить его от неизвестного разработчика (Unknown Developer).

На этом этапе вы можете попробовать простой и быстрый тест FPC — Тестирование установки FPC.

Установка Lazarus

Крайне важно, чтобы совместимый компилятор Free Pascal (FPC) и его исходный код был установлен перед установкой Lazarus IDE.

Light bulb  Примечание: Для установки на Apple Silicon/AArch64 обратитесь к инструкциям Lazarus Fixes 2.2 или Lazarus development, чтобы создать собственную IDE Lazarus. Перейдите к инструкциям по сборке и используйте загрузку исходного кода Lazarus Fixes 2.2/Lazarus development по своему усмотрению.

Загрузите и установите Lazarus IDE из области файлов Lazarus IDE. Когда вы доберетесь до этой области файлов, выберите правильную версию вашей операционной системы. Подавляющее большинство пользователей Mac теперь должны выбирать 64-битные пакеты в каталоге Lazarus macOS x86-64. Каждый компьютер Mac с конца 2006 года поддерживает 64-разрядную версию. Тот факт, что Apple полностью отказалась от 32-битной поддержки в macOS 10.15 Catalina (выпущенной в октябре 2019 года), является еще одной причиной для выбора 64-битных пакетов.

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

В версиях 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 Debugger2.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".

Параметр "debug info" влияет только на модули непосредственно в вашем проекте. Однако модули в пакетах также могут иметь отладочную информацию. Это может быть

  • установка в пакете
  • для многих, но не для всех пакетов в меню Tools(Сервис) > Configure build Lazarus(Настройка сборки Lazarus)
  • project settings (настройки проекта) > Дополнения и переопределения

Если вы измените настройки для пакета, вы также можете проверить, в какой пакет вы планируете перейти. Пакет, в который вы не входите, не требует отладочной информации. Если вы используете тип из пакета (такой, как TForm из LCL), то достаточно, чтобы ваш модуль (в котором вы объявляли переменную и(или) использовали переменную для включения типа) имел отладочную информацию. Уменьшение количества пакетов с отладочной информацией (в том числе тех, которые по умолчанию имеют отладочную информацию) может сократить время запуска отладчиков.

Также, возможно, стоит сравнить (не проверено) время запуска отладчиков для тех же настроек, только изменив флажок "use external debug info" (использовать внешнюю информацию отладки).

Это должно быть установлено только в вашем проекте. Если установлен в вашем проекте, это повлияет на все пакеты. (Если он установлен в пакете, он ничего не сделает/по крайней мере, не должен ...)

Установка LazDebuggerFpLLdb

Если вы установились из исходного кода и [при этом] использовали параметр bigide [утилиты make], то правильный отладчик будет установлен, как пакет, и [сразу будет] готов к работе. Однако, если вы установили другим способом, [отладчика] там может и не оказаться. На главном экране IDE выберите Packages(Пакеты) -> Install/Uninstall Packages (Установить/удалить пакеты). Show - это два списка пакетов, слева - список уже установленных, справа - доступных для установки. Ищите LazDebuggerFpLldb (именно его, есть некоторые схожие названия, но менее подходящие пакеты). Если он справа, щелкните его, нажмите "Install Selection" (Установить выделенное), а затем "Save and rebuild IDE" (Сохранить и пересобрать IDE). Это займет немного времени, IDE выключится и перезапустится, и все должно быть хорошо. Теперь вернитесь на страницу и продолжите настройку отладчика.

Cocoa 64-бит в сравнении с Carbon 32-бит

Использование 64-битной платформы Cocoa от Apple теперь, несомненно, является будущим для Mac. 32-разрядная платформа Apple Carbon, хотя больше не разрабатывается, но работает почти так же, как и ожидалось. Однако мы бы порекомендовали сначала попробовать Cocoa, поскольку Apple прекратила поддержку 32-разрядных приложений и 32-разрядной платформы Carbon в macOS 10.15 Catalina (октябрь 2019 г.) .

Можно собрать Cocoa-версию Lazarus IDE, начиная с версии 2.0.0 и выше. Также можно собрать Carbon-версию Lazarus IDE (если вы не используете macOS 10.15 Catalina или более позднюю версию) и использовать ее для создания 64-битных двоичных файлов Cocoa.

Чтобы создавать приложения Cocoa в Carbon или Cocoa IDE, вам необходимо установить Target для 64-битного процессора и выбрать набор виджетов Cocoa:

  • Откройте свой проект с помощью Lazarus и в меню выберите Project > Project Options.
  • На панели "Config and Target" (Конфигурация и цель) установите для "Target CPU family"(Целевое семейство ЦП) значение "x86_64" (Intel) или "aarch64" (Apple M1).
  • На панели "Config and Target" (Конфигурация и цель), если "Current LCL widgetset"(Текущий набор виджетов LCL) не установлен для Cocoa, нажмите "Select another LCL widgetset" (Выбрать другой набор виджетов LCL), который перенесет вас на панель "Additions and Overrides" (Дополнения и перекрытия), где вы можете нажать выпадающее меню "Set LCLWidgetType"(Присвоить "LCLWidgetType") и установите значение "Cocoa"
  • Убедитесь, что в разделе Tools (Сервис) > Options(Настройки) (> Preferences (Параметры) для Lazarus в версии 2.2.0 и более поздних версиях) для параметра "Compiler Executable" (Исполнимый файл компилятора) установлено значение «/usr/local/bin/fpc», чтобы получить 64-разрядные приложения.
  • Теперь скомпилируйте свой проект и, пожалуйста, сообщите о любых проблемах, с которыми вы столкнулись.

Матрица совместимости FPC + Lazarus

Не всякая комбинация [версий] Lazarus и Free Pascal совместима с любой установкой macOS. Пожалуйста, обратитесь к следующей таблице, чтобы найти правильную версию для вашей среды разработки:

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.

Installing non-release versions of the Lazarus IDE

Lazarus Fixes 2.2

There are a number of reasons why you may be better off using a non-release version of Lazarus, specifically, fixes_2_2. Particularly:

  • You almost certainly need to target 64 bit Cocoa, macOS 10.15 Catalina and later do not support 32 bit Carbon at all.
  • The Cocoa widget set has steadily improved and the lldb debugger interface has rapidly improved, since even v2.0.0.
  • If your Mac has an Apple M1 Processor, the debugger in fixes_2_2 now works for aarch64.
  • Fixes_2_2 is a safer and more stable option than the development branch, but still gets the new features much faster than the release version.

Pre-compiled binaries based on fixes_2_2 are not available from SourceForge so we download and build from the source code. A little slow initially but very reliable and a great test of your compiler install ! You will need git which is included in all recent versions of the Xcode command line tools which you should have already installed (see Xcode Command Line Tools above).

About svn or git: The Xcode 11.4 command line tools on macOS 10.15 no longer install svn, only git. You can install subversion via fink, ports or brew.


  • When working with an Apple Silicon M1 processor Mac ensure you use the FPC 3.2.2 or later as it provides a universal binary with both a native aarch64 and Intel compiler. If you must use an earlier FPC than 3.2.2 see Apple Silicon Support for how to do this. When building the Lazarus IDE, change the CPU_TARGET in the instructions below from x86_64 (Intel 64 bit) to aarch64 (ARM 64 bit - Apple Silicon M1).

Downloading Lazarus Fixes 2.2 source

Create a directory for Lazarus and download the current fixes version:

cd
mkdir -p bin/lazarus
cd bin/lazarus

Using git:

git clone -b fixes_2_2 https://gitlab.com/freepascal.org/lazarus/lazarus.git laz_fixes

Using svn:

svn checkout https://github.com/fpc/Lazarus/branches/fixes_2_2 laz_fixes

Depending on your internet connection and server congestion this takes a few seconds or a few minutes.

Updating Lazarus Fixes 2.2 source

To keep your fixes_2_2 installation up to date is as easy as:

Using git:

cd ~/bin/lazarus/laz_fixes
git clean -f -d
git pull

Using svn:

cd ~/bin/lazarus/laz_fixes
svn clean --remove-unversioned
svn update

Building Lazarus Fixes 2.2 source

cd laz_fixes
make distclean all LCL_PLATFORM=cocoa CPU_TARGET=x86_64 bigide
//-wait some time...
open startlazarus.app --args "--pcp=~/.laz_fixes"
  • Note I pass a parameter to use a config directory that is based on the name of the actual install directory. It makes some scripting easy.
  • On older macOS versions supporting 32 bit applications, replace the above make line with "make LCL_PLATFORM=carbon CPU_TARGET=i386 bigide " and set up your project as mentioned in the Carbon and Cocoa section below.

You might like to put a small script in your $HOME/bin directory and even set a path to it (very UNIX!)

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

Lazarus development version

Precompiled binaries based on the development version (was known as "trunk" in SVN; now known as "main" in GIT) of the Lazarus IDE are not available from SourceForge, so here's how to download the development version source using svn or git and build the Lazarus IDE. You will need svn (before macOS 10.15 - Catalina) or git (after macOS 10.14 - Mojave) which is included in the standalone Xcode command line tools which you should have already installed (see Xcode Command Line Tools above).


  • When working with an Apple Silicon M1 processor Mac ensure you use the FPC 3.2.2 or later as it provides a universal binary with both a native aarch64 and Intel compiler. If you must use an earlier FPC than 3.2.2 see Apple Silicon Support for how to do this. When building the Lazarus IDE, change the CPU_TARGET in the instructions below from x86_64 (Intel 64 bit) to aarch64 (ARM 64 bit - Apple Silicon M1).

Downloading Lazarus development version source

cd
mkdir -p bin/lazarus
cd bin/lazarus

Using git:

git clone -b main https://gitlab.com/freepascal.org/lazarus/lazarus.git laz_main

Using svn:

svn checkout --depth files https://github.com/fpc/Lazarus/branches all
cd all
svn update --set-depth infinity main

The above svn invocation is more complex due to a bug in many versions of Subversion. This workaround was the work of Alfred (aka Don Alfredo in the Forum) who is the wizard behind fpcupdeluxe.

Updating Lazarus development version source

To update your existing Lazarus development version source.

Using git:

cd ~/bin/lazarus/laz_main
git clean -f -d
git pull

Using svn:

cd ~/bin/lazarus/laz_trunk
svn cleanup --remove-unversioned
svn update

Building Lazarus development version source

make distclean all LCL_PLATFORM=cocoa CPU_TARGET=x86_64 bigide
//-wait some time...
open startlazarus.app --args "--pcp=~/.laz_dev"

What does the bigide make argument do?

The bigide make argument adds a bunch of packages to Lazarus that many find useful and cannot do without. The packages that are added are:

  • cairocanvas
  • chmhelp
  • datetimectrls
  • externhelp
  • fpcunit
  • fpdebug
  • instantfpc
  • jcf2
  • lazcontrols
  • lazdebuggers
  • lclextensions
  • leakview
  • macroscript
  • memds
  • onlinepackagemanager
  • pas2js
  • PascalScript
  • printers
  • projecttemplates
  • rtticontrols
  • sdf
  • sqldb
  • synedit
  • tachart
  • tdbf
  • todolist
  • turbopower_ipro
  • virtualtreeview

The above list is sourced from the [Lazarus source directory]/IDE/Makefile.fpc and may be subject to change.

Note that if you have not compiled your own Lazarus IDE with the bigide argument, you can install any of these packages yourself using the Lazarus IDE Package > Install/Uninstall Packages... dialog.

Installing non-release versions of FPC

Installing from source

There are two current non-release branches of the Free Pascal Compiler: the development (trunk) branch and the Fixes 3.2 branch which includes additional fixes to the released 3.2.2 version. Developers, and those who like living on the bleeding edge and testing new features and fixes, will choose the development version; more normal users, who wish to use a stable branch with some additional fixes since the latest release version, will choose the Fixes branch. The instructions below cover both these branches.

The source code is kept in a version control system called git:

  • macOS 10.5 and higher already contain a command line git client if you have installed the Xcode command line utilities.
  • You also need the latest released Free Pascal Compiler version (3.2.2 as of March 2022) installed in order to be able to successfully compile the development (trunk) version.
Light bulb  Примечание: When building a native aarch64 Free Pascal Compiler (ppca64) for an Apple Silicon M1 processor Mac, change the CPU_TARGET in the instructions below from x86_64 (Intel 64 bit) to aarch64 (ARM 64 bit - Apple Silicon M1) and change any reference to ppcx64 to ppca64

FPC development version

Note that since the development version of FPC (was known as "trunk" in SVN; now known as "main" in GIT) is by definition still under development, some of the features may still change before they end up in a release version.

Create a directory where you would like to put the source (eg fpc_main in your home directory). You don't need to be root to do this. Any normal user can do this. Open an Applications > Utilities > Terminal and do the following:

 []$ git clone -b main https://gitlab.com/freepascal.org/fpc/source.git fpc_main

This will create a directory called fpc_main and download the FPC main source to it.

To subsequently update your local source repository with the latest source changes you can simply do:

 []$ cd
 []$ cd fpc_main
 []$ git clean -f -d
 []$ git pull

To build and install FPC (the highlighted text should be all on one line):

 []$ cd
 []$ cd fpc_main
 []$ make distclean all FPC=/usr/local/lib/fpc/3.2.2/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
 []$ sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64

You will also need to update the links for the compiler in /usr/local/bin which will be pointing to the previous FPC version. For example:

 []$ cd /usr/local/bin
 []$ sudo rm ppc386
 []$ sudo rm ppcx64
 []$ sudo ln -s /usr/local/lib/fpc/3.3.1/ppc386
 []$ sudo ln -s /usr/local/lib/fpc/3.3.1/ppcx64

Note that you will need to build a new ppc386 compiler if you want to continue to compile 32 bit applications by replacing these lines (this is not be possible after Xcode 11.3.1 and macOS 10.14.6 Mojave because of Apple's removal of the 32 bit frameworks):

 []$ make clean all FPC=/usr/local/lib/fpc/3.2.2/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
 []$ sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64

with these two lines:

 []$ make clean all FPC=/usr/local/lib/fpc/3.2.2/ppc386 OS_TARGET=darwin CPU_TARGET=i386 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
 []$ sudo make install FPC=$PWD/compiler/ppc386 OS_TARGET=darwin CPU_TARGET=i386

FPC Fixes 3.2

Create a directory where you would like to put the source (eg fpc_fixes32 in your home directory). You don't need to be root to do this. Any normal user can do this. Open an Applications > Utilities > Terminal and do the following:

 []$ git clone -b fixes_3_2 https://gitlab.com/freepascal.org/fpc/source.git fpc_fixes32

This will create a directory called fpc_fixes32 and download the FPC source to it.

To subsequently update your local copy of the repository source with the latest source changes you can simply do:

 []$ cd fpc_fixes32
 []$ git clean -f -d
 []$ git pull

To build and install FPC (the highlighted text should be all on one line):

 []$ cd
 []$ cd fpc_fixes32
 []$ make distclean all FPC=/usr/local/lib/fpc/3.2.2/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
 []$ sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64

You will also need to update the links for the compiler in /usr/local/bin which will be pointing to the previous FPC version. For example:

 []$ cd /usr/local/bin
 []$ sudo rm ppc386
 []$ sudo rm ppcx64
 []$ sudo ln -s /usr/local/lib/fpc/fixes-3.2/ppc386
 []$ sudo ln -s /usr/local/lib/fpc/fixes-3.2/ppcx64

Note that you will need to build a new ppc386 compiler if you want to continue to compile 32 bit applications by replacing these lines (this may not be possible after Xcode 11.3.1 and macOS 10.14.6 Mojave because of Apple's removal of the 32 bit frameworks):

 []$ make clean all FPC=/usr/local/lib/fpc/3.2.2/ppc386 OS_TARGET=darwin CPU_TARGET=i386 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
 []$ sudo make install FPC=$PWD/compiler/ppc386 OS_TARGET=darwin CPU_TARGET=i386

Known issues and solutions

Lazarus IDE v2.2.0 - rebuilding issue

Any attempt to rebuild the Lazarus IDE from within itself fails with permission errors because the files and directories are owned by a user with the id of 503 whereas most users will find that their id is 501. The solution is to open an Applications > Utilities> Terminal and:

cd /Applications
sudo chown -R your_username Lazarus

The following rebuilding errors do not happen on Intel computers

The next error that occurs is that the resource compiler "fpcres" is not found. The solution is to create a .fpc.cfg (note the initial dot) file in your home directory and add these lines to it:

#include /etc/fpc.cfg
-FD/usr/local/bin

so that "fpcres" can be found where it was installed.

The next error complains of an unsupported target architecture -Paarch64, with the advice to invoke the "fpc" compiler driver instead - except that is what we are doing already. The solution is to go to Lazarus > Preferences > Compiler executable which is set to /usr/local/bin/fpc and change that to /usr/local/lib/fpc/3.2.2/ppca64 instead.

The IDE will now be successfully rebuilt but will not restart automatically. Trying to then start Lazarus from either the startlazarus.app icon or the lazarus.app icon in /Applications/Lazarus still results in the original Intel lazarus binary being launched. The correct aarch64 binary can be found in ~/.lazarus/bin/aarch64-darwin/lazarus. So the final solution is to open an Application > Utilities > Terminal and:

mv /Applications/Lazarus/lazarus /Applications/Lazarus/lazarus.old
mv  ~/.lazarus/bin/aarch64-darwin/lazarus /Applications/Lazarus/

You can then start the IDE with either the startLazarus.app or lazarus.app icons. When you do restart lazarus, it is worth returning to the Lazarus > Preferences > Compiler executable which is set to /usr/local/lib/fpc/3.2.2/ppca64 and changing it back to /usr/local/bin/fpc so that you can compile both aarch64 and Intel binaries to, for example, make a Universal Binary which will run on both Intel and aarch64 machines.

Lazarus IDE - Unable to "run without debugging"

If you are using the Lazarus IDE 2.0.10 and the Run > Run without debugging menu option fails with a dialog similar to:

run dialog fail.png

then you need to patch the Lazarus 2.0.10 source code (Issue #37324 and Issue #36780). Specifically, patch ../ide/main.pp as below (unpatched lines shown first, patched lines shown second):

 7243,7245c7243,7245
 <     if RunAppBundle
 <         and FileExistsUTF8(Process.Executable)
 <     and FileExistsUTF8('/usr/bin/open') then
 ---
 >     if RunAppBundle then
 >     //    and FileExistsUTF8(Process.Executable)
 >     //and FileExistsUTF8('/usr/bin/open') then

and recompile the Lazarus IDE.

Alternatively, you can omit patching the source code and simply recompile Lazarus 2.0.10 with FPC 3.0.4.

A similar patching exercise and recompiling, or simply recompiling with FPC 3.0.4, needs to be done for Lazarus 2.0.8 if it has been compiled with FPC 3.2.0.

Upgrading from Mojave (10.14) to Catalina (10.15)

  • Run sudo xcode-select --install
  • To enable Lazarus to locate the crt1.10.5.o file change in /etc/fpc.cfg the -Fl behind "#ifdef cpux86_64" from
-Fl/Applications/Xcode.app/Contents/Developer/Toolchain...

to

-Fl/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib/

Building the FPC compiler from Mojave (10.14) onwards

  • To find the crt1.10.5.o file when building a later Free Pascal Compiler version from source, you need to specify:
 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"

on the make command line because FPC ignores the /etc/fpc.cfg configuration file during builds of itself.

Mac Installation FAQ

  • See the Mac Installation FAQ for solutions to other common problems that may arise during (and after) installation of Lazarus and Free Pascal on macOS.


Uninstalling Lazarus and Free Pascal

Refer to Uninstalling Lazarus on macOS for uninstallation options.

Legacy Information

See Legacy Information for details of:

  • Installing Lazarus on Mac OS X 10.4 (Tiger), Mac OS X 10.5 (Leopard), OS X 10.8 (Mountain Lion)
  • Installing Lazarus 2.0.8, 2.0.10 with FPC 3.2.0 for macOS 10.10 and earlier
  • Installing Lazarus 2.0.8 with FPC 3.2.0 for macOS 10.11+
  • Installing Lazarus on PowerPC-based Macs
  • Old Xcode versions
  • Installing the gdb debugger
  • Compatibility matrix for Lazarus 1.0.0 through 1.6.4 and FPC 2.6.0 through 3.0.2.

Известные проблемы

  • FPC 2.4.4 имеет ошибку. Вы не можете скомпилировать IDE с флагом проверки диапазона -Cr.
  • В OS X 10.4 вы должны вручную удалить любую предыдущую версию перед установкой нового dmg. Удалите следующие файлы и папки:
    • /Developer/lazarus
    • /Library/Receipts/lazarus.pkg
    • /etc/lazarus
    • /usr/local/bin/lazbuild

См. также

Другие интерфейсы

Платформозависимые советы

  • macOS Programming Tips - Установка Lazarus, полезные инструменты, команды Unix и многое другое ...
  • WinCE Programming Tips - Использование телефонного API, отправка SMS-сообщений и многое другое ...
  • Windows Programming Tips - Советы по программированию настольных приложений Windows.

Mac How в статьях

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

Статьи по разработке интерфейсов

  • Carbon interface internals - Если вы хотите помочь улучшить интерфейс Carbon
  • Windows CE Development Notes - Для карманных ПК и смартфонов
  • Adding a new interface - Как добавить новый интерфейс набора виджетов
  • LCL Defines - Выбор правильных опций для перекомпиляции LCL
  • LCL Internals - Некоторая информация о внутренней работе LCL