Arm elf gcc linux

Лучший способ установить arm-elf-gcc на компьютер с Linux

Привет, ребята, я работаю на устройстве, использующем arm-elf-gcc для компиляции кода для макетной платы MakingThings. Моя машина для разработки — это Linux-система под управлением Ubuntu 9.10. На другом Linux-боксе, использующем Ubuntu, я получил нормально работающий arm-elf-gcc, вручную собрав и установив gcc после 3 или 4 попыток

Я пытаюсь выбрать лучший способ установить набор инструментов, но, похоже, не самый лучший способ AFAIK. Установка на 9.08 и 9.10, похоже, не работает, за исключением случаев, когда я вручную собираю и устанавливаю среду.

Я пробовал пакеты Emdebian и CodeSourery, и ни один из них не работал хорошо.

Есть ли у кого-нибудь еще хорошие предложения для установки arm-elf-gcc на Linux?

Я бы сказал, что CodeSourcery Lite — самый простой способ. Версия Lite — это всего лишь инструменты GNU (никаких модных IDE и т. Д.).

Он устанавливается точно в единый каталог, вам просто нужно указать путь к нему.

Вот довольно хорошая статья, в которой частично рассказывается о создании собственного кросс-компилятора с использованием crosstool-ng . Вы можете найти это полезным, как и я.

Я думаю, что лучший способ — это вручную собрать и установить gcc за одну попытку. 😉

Хотя для этого требуется, чтобы вы делали это пару раз на практике, и мой собственный результат в прошлый раз составлял две попытки (makeinfo отсутствовала при сборке binutils, опять же). Я использую свои собственные скрипты, которые похожи, но раздельно скачивают и собирают.

Источник

Хроники пикирующего дракона

От киборга для киборгов!

Страницы

27 мая 2010 г.

Собираем свой кросскомпилятор для ARM.

Для задачи портирования маленькой RT оси на SDK2.0, внутри которого какой-то ARM7, нужно собрать компилятор, который будет собирать исполняемые файлы под архитектуру ARM, работая при этом на машине с x86_64 процессором. К сожалению, в интернете практически отсутствуют руководства по сборке своего кросскомпилятора — в основном, рекомендуется использовать какие-то монстры наподобие Buildroot или crosstool-ng, которые помимо кросскомпилятора собирают еще кучу софта, мне ненужного.
Методом «научного тыка» я похоже набрел на последовательность действий, которая позволила мне наконец-то собрать для себя кросскомпилятор.

Для сборки нужны:

  • binutils — утилиты типа ar, nm и т.п.
  • gcc — он будет нашим кросскомпилятором
  • newlib — библиотека языка C, оптимизированная для использования во встраиваемых системах

Для сборки рекомендую выделить отдельный каталог, например

/toolchain-arm, и проводить все последующие действия внутри него.
Для начала скачиваем последнюю версию binutils отсюда. Распаковываем архив и конфигурируем исходники командой:

./configure —prefix=/usr/local/arm-linux/ —target=arm-elf —enable-interwork —enable-multilib —with-float=soft —disable-werror

/.profile и выполнить команду
.

./gcc/libgcc.mvars: Нет такого файла или каталога

sudo ../[gcc-source-dir]/configure —target=arm-elf —prefix=/usr/local/arm-linux/ —enable-interwork —enable-multilib —with-float=soft —enable-languages=»c,c++» —with-newlib —with-headers=../[newlib-source-dir]/newlib/libc/include/ && sudo make && sudo make install

arm-elf-gcc: error trying to exec ‘cc1’: execvp: Нет такого файла или каталога

./configure —target=arm-elf —prefix=/usr/local/arm-linux/ —enable-interwork —enable-multilib —with-float=soft

Осталось только вновь исправить права доступа на подкаталоги в каталоге /usr/local/arm-linux.
Теперь все — у нас есть свой кросскомпилятор для архитектуры ARM!

UPD (03.08.2010):
При сборке простого хелловорлда, у меня внезапно выскочила ошибка:

Источник

Jensd’s I/O buffer

random technotes…

Cross compiling for arm or aarch64 on Debian or Ubuntu

ARM is gaining more and more traction and is growing a lot in popularity. It’s not always possible to build directly on these ARM-based devices, especially when they are limited in resources. The majority of build and developer machines are still on x86 and by using cross compiling, it is possible to build binaries or executables usable on another architecture. For example, to use your standard PC, most likely x86, to build something that is usable on another machine or device that’s on another architecture, like ARM. In this post, I’ll explain how to do cross compiling for 32bit ARM (arm) or 64bit ARM (aarch64) using Debian 10 or Ubuntu 20.04 LTS.

Читайте также:  Recent files windows explorer

Youtube video

If you are interested, I also created a YouTube video from this blogpost. If you prefer classic text, you can just follow the rest of this article:

Introduction

The ability to cross compile, for me, is most used to build troubleshooting tools that are not installed or available on Linux-based devices. For example a device like a Raspberry Pi, NAS, router or an access point that has a custom Linux build without or limited option to install additional packages.

Sample output of a random embedded device running Linux…:

For the steps below, I will be using Debian 10 (Buster) and I will also test the same steps on Ubuntu 20.04.1 (LTS). All steps are verified to be interchangeable between both. The starting point for both is a minimal installation (standard system utilities + SSH server). This makes sure that, if anyone wants to repeat these steps, all is reproducible and nothing is skipped or missed that would be preinstalled already.

Terminology

In cross compiling, the following (confusing) terminology is used:

  • Build platform: Architecture of the build machine
  • Host platform: The architecture you are building for
  • Target platform: The architecture that will handle the compiled binaries

Build and host are more or less clear but target can be confusing. Simply put, target is only relevant when working on development tools (like the compiler itself).

When you are building for the same architecture as which you are using, build, host and target are the same. This is called a “native” compilation. If build and target platform are the same, but host is different, then we’re talking about cross compilation, which this post is covering. When all three platforms are different, it’s called a “canadian”. This is used to build a cross compiler for another architecture.

Just to be clear, in this post, the build and target platform are x86_64 (standard PC) and the host is the ARM platform. I will cover both 32bit ARM (armv6, armv7 or simply arm) and 64bit ARM (aarch64).

ARM architectures

To find out for which of these (32 bit or 64 bit ARM) you need to compile, the easiest is to look at the output of uname -m.

For x86_64 (standard PC):

64 bit ARM (or aarch64):

Prerequisites

Before we can start compiling, we need to install the necessary packages and tools for cross compiling for ARM. These include the standard tools needed for compiling native:

For 32 bit ARM (arm):

For 64 bit ARM (aarch64):

Of course you can install both the necessary compilers for 32 and 64-bit if you plan to compile for both these architectures.

Compiling a simple C program from source

Once we have installed the prerequisites, we can try and compile a simple C program. Let’s first do a so-called native compile for the PC we’re compiling from, just to make sure that our program does what we want.

Save the source as helloworld.c:

Compile the source “native” and write the binary as helloworld-x86_64

To see what type and for which platform the result of our compilation is, we can check the output with the “file”-tool:

We can execute the binary to check the result:

The next step is to compile the same source for ARM. We simply do this by using a different compiler (arm-linux-gnueabi-gcc instead of gcc for 32 bit ARM or gcc-aarch64-linux-gnu for 64 bit ARM or aarch64).

Читайте также:  Сканер для astra linux

For 32 bit ARM (arm):

For 64 bit ARM (aarch64):

As you can see, file gives us a different result, which we would expect.
Trying to execute these binaries on the build machine (x86_64), as expected, will result in an error:

To test if this has worked, we need a machine or device running the architecture for which we built:

As you see in the above output, our small program works fine on ARM after cross compiling it!

Cross compiling with configure and make

The above example was pretty simple but when compiling source from larger projects, it’s usually done by generating a makefile with configure and then running the compile and other necessary steps with make. To replace gcc with another, target platform specific compiler would be a lot of work. Fortunately most of the times you can just specify the platform which you are compiling for when running configure.

As an example, I’ll create a binary for ARM aarch64 of strace. To avoid getting into problems with dependencies on my embedded ARM device, I’ll provide the static option (see below for more explanation).

First step is to get the source of strace from: https://github.com/strace/strace/releases/tag/v5.10 and extract it:

The next step is to run configure. But here we need to specify the build and host platform so that we want to end up with a binary (statically linked) for ARM:

At this point we’re ready to do the actual cross compile by running make:

As you see, I built this one for use on aarch64. If you want to do the same for armv6 or armv7, simply replace –host aarch64-linux-gnu with –host arm-linux-gnueabi when running configure.

Some additional explanation with the flags and arguments I passed to ./configure in order to get this working:

  • checking for library containing timer_create… no
    configure: error: failed to find timer_create
    was fixed by adding LDFLAGS=”-pthread”
  • checking for m32 personality compile support… no
    checking whether to enable m32 personality support… no
    configure: error: Cannot enable m32 personality support
    was fixed by adding –enable-mpers=check

As with the small C-program, it’s time to test the compiled binary on ARM:

This gives us the ability to simply copy and use strace on a random aarch64 machine.

About static linking and dependencies

As I mentioned in the beginning, I mainly use cross compilation to build troubleshooting tools. Often, the platform where you are building for, is limited. This could be due to lack of resources, like an embedded device. But also because pre-built packages are either not available or it’s not possible to install them. In a lot of cases, this also means that installing dependencies for whatever you are building might be a problem. Obviously, these dependencies also have to be built for that same architecture.

If you have this kind of limitation or you simply want your binary to just run on that architecture. Without worrying on dependencies, or conflicting (older) version of those dependencies that might be already installed, you can use static linking. This means that at build time all necessary dependencies will be included in the binary itself.

Static linking has a few drawback as it is potentially unsecure (the included dependencies will not be updated with the system), could cause incompatibility when libraries that do lower level system calls and the resulting binary file will be larger. These are things I can live with when building troubleshooting tools as they are not intended for long-time use.

While static linking might be what you are looking for, it’s not always be easy to accomplish. Especially in combination with cross compilation it can give you a headache. Most tools depend on libc or glibc, which discourages static linking for the good reasons I mentioned in the paragraph above. Fortunately there is a libc implementation that was developed from scratch and that allows proper static linking for libc-dependencies: musl (pronounce as musscle).

Читайте также:  Пропали данные с рабочего стола windows 10

Cross compiling with configure and make using the musl libc implementation

To make use of musl, we need to download the correct version for our cross compilation. You can find a full list over here: https://musl.cc/#binaries.

After the download, we can extract the archive and test if this works on our build machine:

Next, I will build a static linked version of TCPdump for aarch64. Always a nice tool to have handy when you need to log, investigate or troubleshoot network connectivity. Unfortunately tcpdump is not always available or in the best case as a limited Busybox-version.

First, we need to install some required tools, these are used by the tcpdump for the build process:

Next, we need to download the source for both tcpdump and libpcap and extract it. You can find the latetst version over here: https://www.tcpdump.org/index.html#latest-releases

After downloading and extracting the source code, we need to run the configure-script for libpcap first. Only this time, we need to set our compiler to the musl-compiler for our cross compilation by setting CC to: aarch64-linux-musl-gcc:

If all went fine, we can do the actual compilation of libpcap by issuing make:

Now, we can repeat the same (./configure and make) for tcpdump itself. By doing the static linking, libpcap will be included and the result is a single binary tcpdump:

As you can see by the last command, we have our statically linked tcpdump binary. If all goes well, we should be able to execute this, without any further dependencies, on an aarch64-based machine.

As you can see, tcpdump works fine and does not need any dependencies. This is really helpful if you need to work or troubleshoot on platforms that come with a very limited set of tools and no ability to easily install them. You can simply copy the file and it will work.

6 thoughts on “ Cross compiling for arm or aarch64 on Debian or Ubuntu ”

Very helpful. You’ve provided a clear explanations of how to do it, and why each of the steps is needed. It’s a good tutorial that can be used to extend the concepts to more complicated cross compiling.

Thanks you! Nice to get some positive feedback 🙂
Also working on a small YouTube video covering the same.

Awesome content, thanks! 🙂

I have a question, slightly related, but more about shared libraries: suppose I’m able to cross compile a shared library with a bunch of dependencies (100+), and I’d need to deploy it to aarch64, and it needs to be a shared library (because of how many dependencies there are; otherwise the binary would be huge). Since I’ve never done this, my question is pretty basic: what are my next steps? I can probably makes sure that all those dependencies are of the correct version but they’ll (in general) have a different path.

Is there a tutorial and/or tool that you could recommend for automatically linking my library on the aarch64 device?

And thanks for your time!

The aarch64 machine will need those dependencies. Either you could install them through the package manager (if there is any over there) or cross compile these separately. The versions do not need to be an exact match but too far away will probably give you troubles.

About the path they are in, you do not need to worry. At the time of execution, those dependencies/libraries are being searched in LD_LIBRARY_PATH. You check in advance which libs are missing with the ldd command as well.

Источник

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