Compile delphi on linux

Перенос Delphi-программы под Linux

Возникла такая задачка, вот решил поделиться ощущениями.

Не рекомендовано к прочтению тем, кто чувствует себя в линуксе, как рыба в воде — ничего особо интересного вы здесь не узнаете.
Сугубо и трегубо не рекомендовано к прочтению теми, кто простенький парсер пишет на php+mysql, заранее зная, чем это через полгода кончится. Я им завидую, конечно, но читать комментарии «все нормальные люди пишут на. » — уныло и очень бесполезно.

На этом лирику завершаем и устанавливаем Lazarus. Если есть подозрение, что ваша программа использует что-то windows-специфическое, то лучше поставить CodeTyphon (это тот же лазарус с тучей примочек), и после сборки «нормального» лазаруса собрать еще и cross-build примочки.

Не пугайтесь слова «собрать» — для сборки лазаруса+freepascal нужно всего лишь запустить setup.bat и выбрать в нем седьмой пункт, а для сборки cross-build примочек — выбрать в CodeTyphon’овском меню Cross-Build и нужный пункт в подменю. Дальше оно само 🙂

Запускаем Lazarus, меню Сервис — Преобразовать проект Delphi в проект Lazarus. Естественно, перед этим делаем копию проекта.

После преобразования допиливаем напильником то, что не преобразовалось само. В частности, для проекта, использующего Firebird, пришлось изменить название ряда классов, ибо в Lazarus’е они называются иначе.

Следует обратить внимание на то, что многие типы в lazarus тоже называются иначе, это доставило мне несколько десятков неприятных минут в попытках понять, какого же черта types mismatch.

Когда все начнет компилироваться под Windows (запустить программу из-под среды я так и не смог; говорят, что отладчик не дружит с Comodo, даже отключенным, а я не готов сносить comodo), можно изменить настройку Проект — Параметры проекта — Генерация кода на нужную ( i386 — Linux, например) и продолжить допиливание (это в том случае, если вы установили CodeTyphon).
Компилироваться под линукс оно все равно не станет, но надо довести уровень ошибок с понятных до непонятных))) Точнее — до ненайденных библиотек, причем явно не windows’ных.

Далее нам надо скомпилировать то, что получилось, под Linux. Тут есть два пути — допилить lazarus до того состояния, когда он начнет действительно поддерживать кросс-компиляцию или компилировать под Linux’ом.

В интернете можно прочитать, что второй путь проще. Не повторяйте моей ошибки, не сочтите это преувеличением или фигурой речи! Второй путь действительно проще.

Для компиляции под линуксом в виртуальной машине нам понадобится виртуальная машина и дистрибутив. Я взял VirtualBox и сетевой установщик Debian (в советах по допиливанию лазаруса неоднократно писалось, что библиотеки надо брать строго от того линукса, под которым будет работать программа. Не знаю, работает ли это правило для выбора дистрибутива, но рисковать не хотелось).

Читайте также:  Проверка сетевого доступа linux

Создаем виртуальную машину, добавляем общую папку с проектом, монтируем диск с дистрибутивом, запускаем. Внимание, клавиша «выхода из окна эмулятора» по умолчанию — правый Ctrl!

С чистой совестью можно выбирать графический установщик, все будет как надо. В процессе отвечаем на энное количество вопросов, ничего особенного в них не содержится. Windows все устанавливали? Практически все то же самое.

Ни в коем случае не забываем логинов и паролей, а то будет очень обидно %-))

В установленном Linux логинимся под не-рутом (под рутом не пускает) и даем себе права администратора: Система — Администрирование — Пользователи и группы. Пригодится, хотя на каждом шагу все равно придется вводить пароль рута.

Графическая оболочка вполне дружелюбна и понятна. Не знаю, как бы оно было на реальной машине, но в виртуальной линукс выглядит весьма достойно, мое впечатление о нем заметно улучшилось.

Далее идем в Система — Администрирование — центр приложений — загрузить, в строчку поиска вводим Lazarus и устанавливаем его, после чего он появляется в меню «Приложения — программирование».
Ставить CodeTyphon не рекомендую, незачем.

Теперь монтируем общую папку.
В домашней папке пользователя создаем папку, на которую отобразится расшаренная папка.
Затем Ctrl+Alt+F1 (это открытие консоли), рутовые логин-пароль ( хинт: перелогиниться можно, введя команду exit. Вполне возможно, что это неправильно, но работает же) , затем
mount -t vboxsf /home// (например: mount -t vboxsf LazarusProject /home/virgo/LazProj)
Ctrl+Alt+F7 (выход из консоли).

Приложения — программирование — Lazarus, открываем проект из нашей расшаренной папки, и. компилируем!

Источник

Delphi cross compiler for linux

I was wondering if there is any Borland cross compiler that can make my windows code work on linux without wine.I’m using winxp with delphi 7. I was always wondering if it was possible to code same tool I coded in windows , again in Linux and how is it possible to code same tool by using pascal code in linux.Thanks

You may wait the next Delphi release (Delphi XE3) that, may be, will be Linux compatible. The EMB roadmap is not very clear but Android/linux is mentionned : blogs.embarcadero.com/jtembarcadero/2011/09/17/…

4 Answers 4

The best solution is Lazarus, the delphi-like GUI for Free Pascal. If you were using «pure» vcl, without Windows internales or any special add-ons the migration will be a pice of cake 🙂 Take a look here: http://lazarus.freepascal.org

BTW — Lazarus and FPC are true mulitplatform — you can compile code for Linux, Windows, MacOS and more with the same codebase 🙂

I downloaded and installed FPC+Lazarus using the CodeTyphon distribution. It supplied all source code of both project, most of the available third-party libraries, and allow to compile cross-platform IDEs from an easy to use interface. I was amazed about how the IDE is mature, easy to use and powerful. And much lighter than Delphi latest IDE (even with a lot of components). And compiling both IDE and compiler from source (in some minutes) is something very very very nice. It changes from the opacity of other solutions.

Читайте также:  Устанавливаем python kali linux

Another IDE using FPC, for both Windows + Linux is MSEGUI. From one man, a whole cross-platform library for writing serious business applications. Very active. Executables are lighter than the one generated by Lazarus (but you lack the VCL layout: this is a whole another framework). See gitorious.org/mseide-msegui

Nevertheless, the only practical way to use Lazarus (in my opinion) is on «projects you start from scratch» — porting a non-trivial Delphi application to use Lazarus+LCL is not practical right now, at least not when I’ve tried it. It’s a long way from «making windows code run on Linux» without WINE, which is what the OP wants, which is, in fact, a pipe dream.

Источник

Linux Application Development

RAD Studio allows you to develop applications for the target Linux platform. Using RAD Studio installed on Windows machine, you can create a 64-bit Linux application and deploy it to the Linux machine. Developing Linux applications is similar to creating Android apps in RAD Studio. However, for Linux, you cannot create the visual VCL and FireMonkey applications. Here is the list of apps that are available for the Linux platform:

  • Console Application
  • EMS Package (RAD Server)
  • DataSnap
  • DataSnap WebBroker
  • WebBroker
  • Dynamic-link Libraries
  • DUnitX Project

Contents

Prerequisites

To develop Linux applications, you need to have the RAD Studio installed on the Windows PC as well as a machine with the Linux platform (can be a virtual machine).

Preparing Your Linux Development Environment

To prepare your development system (PC) and Linux machine for application development with RAD Studio:

Installing Development Packages

To install the development packages on Ubuntu:

  1. Right-click your desktop and select Open Terminal.
  2. To upgrade the packages you have already installed , type sudo apt update && sudo apt upgrade && sudo apt dist-upgrade in the terminal.
  3. Type your user password and press Enter
  4. Wait until prompted to agree to the package upgrade operation. Type Y and press Enter
  5. Wait until the package upgrade operation is complete. It may take a few minutes to complete.
  6. To add the development packages, type sudo apt install joe wget p7zip-full curl openssh-server build-essential zlib1g-dev libcurl4-gnutls-dev libncurses5 in the terminal.
  7. Type your user password and press Enter
  8. Wait until prompted to agree to the package installation operation. Type Y and press Enter
  9. Wait until the pacjage installation operation is complete. It may take a few minutes to complete.
Читайте также:  Lightweight linux desktop environment

To install the development packages on Red Hat:

  1. Right-click your desktop and select Open Terminal.
  2. Type yum groupinstall ‘Development Tools’ in the terminal.
  3. Press Enter and wait until the package installation operation is complete. It may take a few minutes to complete.

Preparing Your Linux Machine

To create Linux applications, you need to add a virtual machine PAServer:

1. Find the LinuxPAServer22.0.tar.gz file in the following location: C:\Program Files (x86)\Embarcadero\Studio\22.0\PAServer\LinuxPAServer22.0.tar.gz 2. Unpack the LinuxPAServer22.0.tar.gz file.

To use the System.zLib unit on Red Hat:

1. Install the zLib-devel library to your RHEL machine with the following command: sudo yum install zlib-devel 2. Update the local SDK cache.

To use the System.zLib unit on Ubuntu:

1. Install the zLib-devel library to your Ubuntu machine with the following command: sudo apt-get install zlib1g-dev 2. Update the local SDK cache.

Creating a Connection Profile

  1. Right-click the folder where you have unpacked the LinuxPAServer22.0.tar.gz file, and then click Open in Terminal.
  2. Enter ./paserver in terminal. Then, press Enter.
  3. On the Tools > Options > Environment Options > Connection Profile Manager page, click the Add button. The Create a Connection Profile wizard opens.
  4. On the Profile information page, enter the following:
    • In the Profile name field, enter the needed name.
    • In the Platform field, click the 64-bit Linux platform.
    • Click Next.
  5. On the Remote machine information page, enter the following:
    • In the Remote machine field, enter the IP address or Machine name.
    • Click Test Connection to check if the values are valid.
  6. Click Finish.

Adding the Installed SDK to RAD Studio

  1. On the Tools > Options > Environment Options > SDK Manager page, click the Add button.
  2. In the Add a New SDK dialog, enter the following:
    • In the Select a platform field, click 64-bit Linux.
    • In the Select a profile to connect, select a created profile from the drop-down list.
    • In the Select an SDK version field, the name of the SDK that you just installed will automatically appear. If you have not installed SDK previously, you can do it on this step. If you have already installed SDK, move on to the next step.

Running PAServer on Linux machine

To run the PAServer on your Linux machine:

Developing Your Application

  1. Select the project type for your Delphi application.
    • File > New > Other > Delphi Projects:
      • Console Application
      • DUnitX Project
      • Dynamic-link Library
      • Package
    • File > New > Other > Delphi Projects > DataSnap Server:
      • DataSnap Server
      • DataSnap WebBroker
    • File > New > Other > Delphi Projects > WebBroker > WebBroker Application

See Also

Источник

Оцените статью
Adblock
detector