Arch linux cross build

Distcc Cross-Compiling

Disclaimer: This guide will appear vague and incomplete if you aren’t sure what you’re doing. This is intentional. This is specifically not designed for users new to software compilation and toolchain components.

This is the official cross-compiling method used at Arch Linux ARM. If you plan on building a lot of packages and want to speed up the process, the following guide will turn an x86 Linux computer into an ARM cross-compiler. It’s also much easier than most cross-compile setups.

This guide makes use of distcc in order to not have to build a full ARM development environment on x86. As the distcc project website states, «distcc does not require all machines to share a filesystem, have synchronized clocks, or to have the same libraries or header files installed.» This is particularly advantageous to us since all that is needed is a working cross-compiler for ARM on a faster machine, while controlling the build from an ARM computer that has all of the current libraries and headers.

Distcc

Before beginning, a distcc environment needs to be set up. Follow the Distributed Compiling guide to establish a master system. The x86 machines will be known as the clients.

Pre-built crosstool-ng toolchains

In lieu of building the toolchain as detailed below, if you are running a 64-bit Linux installation you can use these packaged toolchains that are employed in the official build system.

It is highly recommended to use these tarballs as they have been thoroughly tested, and are maintained to be version- and source-matched to the current toolchain components for our ARM architectures. If you build the toolchain yourself, you must assemble patched source tarballs to build versions that match what is in use here.

Building a crosstool-ng toolchain

This process is very automated, courtesy of crosstool-ng. As a normal user (not root!), clone revision c206f2fc of the git repository into a directory called «cross» in your home directory. Enter the source directory and configure with a prefix for the «cross» directory, make, and make install. If you are missing any pre-requisites, the configure script will let you know what they are.

mkdir -p cross/src cd cross git clone https://github.com/crosstool-ng/crosstool-ng.git cd crosstool-ng git checkout c206f2fc ./bootstrap ./configure --prefix=/home/your_user/cross make make install

At this point crosstool-ng is ready to be configured. The program «ct-ng» in the «bin» directory is where the magic happens. It also has a menu configuration like the Linux kernel.

Читайте также:  Linux краткий справочник команд

Downloading a CrossTool Configuration

Download the default .config file to place in «~/cross/bin» as shown below. Once you do this, do not run «menuconfig» or values will be overwritten. Choose either v7 or v8 depending on the target platform.

cd /home/your_user/cross/bin wget http://archlinuxarm.org/builder/xtools/xtools-dotconfig-[v7|v8] -O .config

Build the cross-toolchain

cd /home/your_user/cross/bin ./ct-ng build

Make nice with distcc

The toolchain will install under «~/x-tools7h» for armv7 hard-float and «~/x-tools8» for AArch64. You can move this somewhere else if you like, or leave it where it is. Before we can use the compiler binaries that were created, links need to be created to make their names more appropriate. When compile jobs are sent to distcc, the program specified in the CC environment variable on the build master is what gets executed on the build clients. All the binaries that have been produced by crosstool-ng are in the correct format specifying the target platform as a prefix, though not with the correct platform and lacking tuple-less variants. This script will fix our problem. Make «~/x-tools[6h|7h|8]/arm-unknown-linux-gnueabi[hf]/bin/» writable and in there create a file called «link» and paste the following into it. Uncomment for your target architecture and run it.

#!/bin/bash for file in `ls`; do if [[ "$file" == "link" ]]; then continue fi # uncomment for v7 # ln -s $file $ # ln -s $file armv7l-unknown-linux-gnueabihf-$ # uncomment for v8 # ln -s $file $ done

Now the «bin» directory contains links with names that distcc will play nice with.

Compile!

Back on ARM master device, make sure that distcc has been enabled in makepkg.conf per the Distributed Compiling guide. Now all builds using makepkg will make use of the distcc and cross compiler setup.

Crap, it’s not working

If you’ve followed this guide to the letter and you know you’ve done everything right, the likely problem is that the user distccd is running as does not have permission to access the location of the crosstool-ng binaries. Either change distccd’s user or relocate the x-tools directory to somewhere it can read it, then be sure the PATH set above reflects the new location.

Copyright ©2009-2022 Arch Linux ARM
The registered trademark Linux® is used pursuant to a sublicense from LMI, the exclusive licensee of Linus Torvalds, owner of the mark on a world-wide basis.
The Arch Linux™ name and logo are used under permission of the Arch Linux Project Lead.

Читайте также:  Linux find all directories named

Источник

Cross-compiling tools package guidelines (Русский)

Совет: В качестве альтернативы для создания кросс-компиляторных пакетов вы можете использовать crosstool-ng и создайте свой собственный набор инструментов полностью автоматизированным способом. crosstool-ng можно найти на crosstool-ng .

Важная заметка

На этой странице описан новый принцип работы, основанный на следующих пакетах:

  • mingw-w64-gcc и другие пакеты из mingw-w64-* серии
  • arm-none-eabi-gcc и другие пакеты из arm-none-eabi-* серии
  • другие пакеты из arm-wince-cegcc-* серии

Совместимость версий

Важно: Использование несовместимых версий пакетов для компиляции цепочек инструментов приводит к неизбежным сбоям. По умолчанию считают все версии несовместимыми.

Следующая стратегия позволяют выбирать совместимые версии gcc, binutils, ядра и библиотеки C:

  • Основные правила:
    • существует корреляция между выпусками gcc и binutils, используйте одновременно выпущенные версии;
    • лучше использовать последние заголовки ядра для компиляции libc, но использовать переключатель —enable-kernel (специфично для glibc, другие библиотеки C могут использовать другие соглашения) для обеспечения работы на старых ядрах;

    Сборка кросс-компилятора

    Общий подход к созданию кросс-компилятора:

    1. binutils: Создание cross-binutils, которая связывает и обрабатывает для целевой архитектуры
    2. headers: Установите набор библиотеки C и заголовками ядра для целевой архитектуры
      1. используйте linux-api-headers в качестве ссылки и передайте ARCH=target-architecture для make
      2. создать пакет заголовков libc (описан процесс для Glibc here)

      Источник заголовков и libc будет отличаться для разных платформ.

      Совет: Точная процедура может сильно варьировать, в зависимости от ваших потребностей. Например, если вы хотите создать «клон» системы Arch Linux с теми же версиями ядра и glibc, вы можете пропустить сборку заголовков и передать —with-build-sysroot=/ в configure .

      Наименование пакета

      В имени пакета не должно быть префикса со словом cross- (было предложено ранее, но не было принято в официальных пакетах, возможно, из-за дополнительной длины имен), и должно состоять из имени пакета с префиксом GNU triplet без поля поставщика или со значением «unknown» в поле поставщика; пример: arm-linux-gnueabihf-gcc . Если существует более короткое соглашение об именах (например, mips-gcc ), его можно использовать, но это не рекомендуется.

      Размещение файлов

      Последние версии gcc и binutils используют не конфликтующие пути для sysroot и библиотек. Исполняемые файлы должны быть помещены в /usr/bin/ , чтобы предотвратить возникновение конфликтов, перед всеми ними необходимо указать префикс имени архитектуры.

      Правило, ./configure будет иметь по крайней мере следующие параметры:

      _target=your_target _sysroot=/usr/lib/$ . ./configure \ --prefix=$ \ --sysroot=$ \ --bindir=/usr/bin

      где your_target может быть, например, «i686-pc-mingw32».

      пример

      Это PKGBUILD для binutils для MinGW. Вещи, на которые стоит обратить внимание:

      • указание корневого каталога кросс-окружения
      • использование переменных $ , $ и $ , чтобы сделать код более читабельным
      • удаление дублированных / конфликтующих файлов
      # Maintainer: Allan McRae # cross toolchain build order: binutils, headers, gcc (pass 1), w32api, mingwrt, gcc (pass 2) _target=i686-pc-mingw32 _sysroot=/usr/lib/$ pkgname=$=2.10.1' 'zlib') options=('!libtool' '!distcc' '!ccache') source=(http://ftp.gnu.org/gnu/$/$.tar.bz2) md5sums=('09a8c5821a2dfdbb20665bc0bd680791') build() < cd $/$ mkdir binutils-build && cd binutils-build ../configure --prefix=$ --bindir=/usr/bin \ --with-sysroot=$ \ --build=$CHOST --host=$CHOST --target=$ \ --with-gcc --with-gnu-as --with-gnu-ld \ --enable-shared --without-included-gettext \ --disable-nls --disable-debug --disable-win32-registry make make DESTDIR=$/ install # clean-up cross compiler root rm -r $/$/ >

      Примечание: Во время построения кросс-цепочки всегда выполняйте команды configure и make из определенного каталога (так называемая компиляция вне дерева) и удаляйте весь каталог src после малейшего изменения в PKGBUILD.

      Как и почему

      Почему бы не устанавливать в /opt

      1. Во-первых, согласно Стандарту Файловой Иерархии, эти файлы просто принадлежат /usr . И точка!
      2. Во-вторых, установка в /opt является последней мерой, когда другой опции нет.

      What is that out-of-path executables thing?

      Эта статья или раздел нуждается в переводе

      This weird thing allows easier cross-compiling. Sometimes, project Makefiles do not use CC & co. variables and instead use gcc directly. If you just want to try to cross-compile such project, editing the Makefile could be a very lengthy operation. However, changing the $PATH to use «our» executables first is a very quick solution. You would then run PATH=/usr/arch/bin/:$PATH make instead of make .

      Поиск проблемы

      Что делать, если компиляция не удалась без четкого сообщения?

      Если ошибка возникла во время выполнения configure , прочитайте $srcdir/pkgname-build/config.log . Для ошибки, произошедшей во время компиляции, прокрутите консоль, войдите в систему или найдите слово «error».

      Что означает эта ошибка [error message]?

      Скорее всего, вы допустили некоторые неочевидные ошибки:

      • Слишком много или слишком мало флагов конфигурации. Попробуйте использовать уже проверенный набор флагов.
      • Зависимости повреждены. Например, неуместные или отсутствующие файлы binutils могут привести к загадочной ошибке во время настройки gcc.
      • Вы не добавили export CFLAGS=»» в свою функцию build() (см. bug 25672 в GCC Bugzilla).
      • Для некоторых комбинаций —prefix / —with-sysroot может потребоваться, чтобы каталоги были доступны для записи (что не очевидно из руководства clfs).
      • В sysroot нет ни заголовков ядра или libc.
      • Если google не помогает, отмените текущую конфигурацию и попробуйте более стабильную/проверенную.

      Почему файлы устанавливаются в неправильных местах?

      Различные методы запуска make install приводят к разным результатам. Например, некоторые цели make могут не обеспечивать поддержку DESTDIR , а вместо этого требуют использования install_root . То же самое для tooldir , prefix и других подобных аргументов. Иногда предоставление параметров в качестве аргументов вместо переменных среды, например

      и наоборот, может привести к различным результатам (часто вызванным рекурсивным самовывозом configure/make).

      Смотрите также

      Источник

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