Программирование для linux delphi

Перенос 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 (в советах по допиливанию лазаруса неоднократно писалось, что библиотеки надо брать строго от того линукса, под которым будет работать программа. Не знаю, работает ли это правило для выбора дистрибутива, но рисковать не хотелось).

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

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

Читайте также:  Мой ip адрес узнать линукс

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

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

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

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

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

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

Источник

Get started writing Linux apps with Delphi 10.3 and 10.4

Firstly, you need an Ubuntu installation. If you don’t have a physical machine with Ubuntu, you may chose a suitable Virtual Machine, such as VMWare, VirtualBox or Hyper-Visor.

I chose Hyper-V since it is included with Windows 10.

To enable Hyper-V on your Windows installation, Open the “Windows Features” tool and check Hyper-V. If you alse use Visual Studio, you may want to add Windows Hypervisor Platform as well.

A word of advice with regards to storage: Place your VMs on an SSD disk.

Reboot your Windows installation if so instructed.

When ready, Start Hyper-V Manager, and chose Actions | Quick Create… | Ubuntu 18.04.3 LTS

A 1.6Gb download will pursue, so the time depends on your bandwidth.

Before firing up the VM, tweak the new VM config to f.x. 4 CPUs and 8192Mb RAM to give the VM some juice, then power up and go through the base installation.

To manually add the build tools for Ubuntu, open a terminal, and run

sudo apt update sudo apt install build-essential

The first ensures your VM pull all relevant updates, and the second installs gcc and the suite of build tools for Linux.

Note that you can install PAServers for both Rio and Sydney. Just remember to edit the paserver.config and change the default port number for one of them.

Install it to a folder of your liking, as per the instructions in the link and start ./paserver and enter the (optional) password you want the PAServer to use.

To find the IP address of your local Ubuntu VM, open a terminal and run

The IP address we are looking for is in address 2 – in this case: 172.17.202.68

When you first try to compile a Linux app, start with something simple like a console application.

program LinuxTest;  uses System.SysUtils; begin try try Writeln('Hello whirled'); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; finally Write('Press Enter: '); Readln; end; end.

On the first ever compile, the IDE will prompt you for a connection profile.

Читайте также:  Linux md5 all files

Since we didn’t change the configuration, all we need is to fill in the IP address for the host name.
If you entered a password when starting the PAServer, that password is needed here. Remember to click on Test Connection to verify that the PAServer is reachable.

On the first connection, the IDE will download the SDK through the PAServer. This takes a little while and the progress is presented on a desktop-always-on-top progress dialog which is somewhat annoying if you want to do something else while waiting.

After it is complete, you will have a collection of files that allows the linker to find the right link targets for your Ubuntu host.

At this point, your simple console app should be ready to run. It will compile, link, and then upload it to the Ubuntu VM and start it through the PAServer.

By default, it seems that we won’t get to see the actual console where the app runs when run through PAServer, so if you want to run it manually – locate the uploaded file on your installation.
It will typically reside under a long path that reflects the name of your connection and your Windows username. The PAServer folder will be in the same folder where you installed the PAServer-20.0 (if you are using 10.3.3).

Under scratch-dir, you find the folders for your winuser-connection combos.

Under there again, you will find a folder that matches your Delphi project name, and in that folder your executable which you can start with “./exename”.

At this point, you should be able to do the same.

The next step is to download FMX for Linux via GetIt.
Then you can get started on something beautiful like this 😎
File | New | Multi-device application – change target to Linux 64-bit and run!

Lars Fosdal, August 26th, 2020

Postscript:
I have also done this on VirtualBox, but when comparing Hyper-V and VirtualBox it is clear that Hyper-V is much better at managing HW resources – preventing the constant buzz of the CPU cooling fan which was quite annoying when using VirtualBox.

Источник

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.
Читайте также:  Linux image for docker

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 LinuxPAServer21.0.tar.gz file in the following location: C:\Program Files (x86)\Embarcadero\Studio\21.0\PAServer\LinuxPAServer21.0.tar.gz 2. Unpack the LinuxPAServer21.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 LinuxPAServer21.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