1. Введение

This document describes how to build the LinuxCNC software from source. This is primarily useful if you are a developer who is modifying LinuxCNC. It can also be useful if you’re a user who is testing developer branches, though then you also have the option of just installing Debian packages from the buildbot (http://buildbot.linuxcnc.org) or as a regular package from your Linux distribution (https://tracker.debian.org/pkg/linuxcnc). Admittedly, this section also exists since LinuxCNC is a community effort. and you are encouraged to contribute to the development of LinuxCNC. Generally, you want to compile LinuxCNC yourself for immediate functional access * to a new development of LinuxCNC or * a new development you perhaps want to contribute to LinuxCNC or help other completing it.

You may for instance be porting LinuxCNC to some new Linux distribution or, and this common, a developer reacts to you reporting a problem whose fix you want to test. Any such change will see no buildbot to help, or that help is delayed, pending someone else’s review that you do not want to wait for or you are the only other individual with a particular hardware to test the code.

Besides the programs that control your machine that are built from the source tree, you can also build the same PDFs and/or HTML files that you are likely to have encountered online on https://linuxcnc.org/documents/.

If you want to contribute to LinuxCNC but are uncertain about where to start, please seriously consider to contribute to the documentation. Everyone always finds something to improve - and if you only leave a "FIXME: with a comment" in the text as a reference for yourself and others to revisit a section later. Also, translations to languages other than English are very likely to benefit from your scrutiny at https://hosted.weblate.org/projects/linuxcnc/ .

2. Downloading source tree

The LinuxCNC project git repository is at https://github.com/LinuxCNC/linuxcnc. GitHub is a popular git hosting service and code sharing website.

To retrieve the source tree you have two options:

Download tarball

On the LinuxCNC project page in GitHub find a reference to the "releases" or "tags", click that hyperlink to the archive page and download the latest .tar file. You will find that file compressed as a .tar.xz or .tar.gz file. This file, commonly referred to as a "tarball" is an archive very analogous to a .zip. Your Linux desktop will know how to treat that file when double-clicking on it.

Prepare a local copy of the LinuxCNC repository

You would first install the tool "git" on your machine if it is not available already (sudo apt install git). Then prepare a local instance of the source tree as follows: .

$ git clone https://github.com/LinuxCNC/linuxcnc.git linuxcnc-source-dir

. The first argument to the git command gives it away: This is called a "clone" of the LinuxCNC repository. The advantage is that this local clone supports the communication about changes you may decide to perform on the source tree.

GitHub is an infrastructure on its own and explained in depth elsewhere. Just to get you motivated if you do not know it already.offers to perform a clone for you and have that instance made publicly available. GitHub refers to such an additional instance of another repository as a "fork". You can easily (and at no cost) create a fork of the LinuxCNC git repository at GitHub, and use that to track and publish your changes. After creating your own GitHub fork of LinuxCNC, clone it to your development machine and proceed with your hacking as usual.

We of the LinuxCNC project hope that you will share your changes with us, so that the community can benefit from your work. GitHub makes this sharing very easy: After you polish your changes and push them to your github fork, send us a Pull Request.

2.1. Быстрый старт

Для нетерпеливых попробуйте следующее:

$ git clone https://github.com/LinuxCNC/linuxcnc.git linuxcnc-source-dir
$ cd linuxcnc-source-dir/src
$ ./autogen.sh
$ ./configure --with-realtime=uspace
$ make

That will probably fail! That doesn’t make you a bad person, it just means you should read this whole document to find out how to fix your problems. Especially the section on Satisfying Build Dependencies.

If you are running on a realtime-capable system (such as an install from the LinuxCNC Live/Install Image, see the Realtime section below), one extra build step is needed at this time:

$ sudo make setuid

После того, как вы успешно собрали LinuxCNC, пришло время запустить тесты:

$ source ../scripts/rip-environment
$ runtests

This might fail, too! Read this whole document, especially the section on Setting up the test environment.

3. Поддерживаемые платформы

Проект LinuxCNC нацелен на современные дистрибутивы на основе Debian, включая Debian, Ubuntu и Mint. Мы постоянно тестируем на платформах, перечисленных на http://buildbot.linuxcnc.org.

LinuxCNC builds on most other Linux distributions, though dependency management will be more manual and less automatic. Patches to improve portability to new platforms are always welcome.

3.1. В реальном времени

LinuxCNC is a machine tool controller, and it requires a realtime platform to do this job. This version of LinuxCNC supports the following platforms. The first three listed are realtime operating systems:

RTAI

From https://www.rtai.org. A Linux kernel with the RTAI patch is available from the Debian archive at https://linuxcnc.org. See Getting LinuxCNC for installation instructions.

Xenomai

С сайта https://xenomai.org. Вам придется скомпилировать или получить ядро Xenomai самостоятельно.

Preempt-RT

From https://rt.wiki.kernel.org. A Linux kernel with the Preempt-RT patch is occasionally available from the Debian archive at https://www.debian.org, and from the wayback machine at https://snapshot.debian.org.

Не в реальном времени

LinuxCNC также можно собрать и запустить на платформах, не работающих в реальном времени, таких как обычная установка Debian или Ubuntu без какого-либо специального ядра реального времени. . В этом режиме LinuxCNC бесполезен для управления станками, но он полезен для имитации выполнения G-кода и для тестирования частей системы, не работающих в реальном времени (таких как пользовательские интерфейсы и некоторые виды компонентов и драйверов устройств). . Чтобы использовать возможности LinuxCNC в реальном времени, некоторые части LinuxCNC должны работать с привилегиями root. Чтобы включить root для этих частей, запустите эту дополнительную команду после make, которая собирает LinuxCNC:

$ sudo make setuid

4. Режимы сборки

There are two ways to build LinuxCNC: The developer-friendly "run in place" mode and the user-friendly Debian packaging mode.

4.1. Сборка для запуска на месте (RIP)

In a Run-In-Place build, the LinuxCNC programs are compiled from source and then run directly from within the build directory. Nothing is installed outside the build directory. This is quick and easy, and suitable for rapid iteration of changes. The LinuxCNC test suite runs only in a Run-In-Place build. Most LinuxCNC developers primarily build using this mode.

Сборка для запуска на месте делается по шагам, описанным в разделе Быстрый старт в верхней части этого документа, возможно, с разными параметрами для src/configure и make.

4.1.1. src/configure параметры

The src/configure script configures how the source code will be compiled. It takes many optional arguments. List all arguments to src/configure by running this:

$ cd linuxcnc-source-dir/src
$ ./configure --help

Наиболее часто используемые параметры:

--with-realtime=uspace

Build for any realtime platform, or for non-realtime. The resulting LinuxCNC executables will run on both a Linux kernel with Preempt-RT patches (providing realtime machine control) and on a vanilla (un-patched) Linux kernel (providing G-code simulation but no realtime machine control).

If development files are installed for Xenomai (typically from package libxenomai-dev) or RTAI (typically from a package with a name starting "rtai-modules"), support for these real-time kernels will also be enabled.
--with-realtime=/usr/realtime-$VERSION

Сборка для платформы реального времени RTAI с использованием более старой модели «ядро реального времени». Для этого необходимо, чтобы у вас было ядро и модули RTAI, установленные в /usr/realtime-$VERSION. Полученные исполняемые файлы LinuxCNC будут работать только на указанном ядре RTAI. Начиная с LinuxCNC 2.7, это обеспечивает наилучшую производительность в реальном времени.

--enable-build-documentation

Сборка документации в дополнение к исполняемым файлам. Эта опция значительно увеличивает время, необходимое для компиляции, так как сборка документации занимает довольно много времени. Если вы не активно работаете над документацией, вы можете опустить этот аргумент.

--disable-build-documentation-translation

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

4.1.2. Параметры make

Команда make принимает два полезных опциональных параметра.

Параллельная компиляция

make takes an optional argument -j N (where N is a number). This enables parallel compilation with N simultaneous processes, which can significantly speed up your build.

A useful value for N is the number of CPUs in your build system.

You can discover the number of CPUs by running nproc.

Сборка только конкретного элемента

Если вы хотите собрать только определенный компонент LinuxCNC, вы можете указать на то, что хотите собрать, в командной строке make. Например, если вы работаете над компонентом с именем froboz, вы можете собрать его исполняемый файл, запустив:

$ cd linuxcnc-source-dir/src
$ make ../bin/froboz

4.2. Сборка Debian пакетов

When building Debian packages, the LinuxCNC programs are compiled from source and then stored in a Debian package, complete with dependency information. This process by default also includes the building of the documentation, which takes its time because of all the I/O for many languages, but that can be skipped. LinuxCNC is then installed as part of those packages on the same machines or on whatever machine of the same architecture that the .deb files are copied to. LinuxCNC cannot be run until the Debian packages are installed on a target machine and then the executables are available in /usr/bin and /usr/lib just like other regular software of the sytem.

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

To build packages is primarily useful when packaging the software for delivery to end users. Developers among themselves exchange only the source code, likely supported by the LinuxCNC GitHub repository referenced below. Also, when building the software for a machine that doesn’t have the build environment installed, or that doesn’t have internet access, one happily accepts a prebuilt package.

Building Debian packages requires the dpkg-buildpackage tool the is provided by the dpkg-dev package. But when building a Debian package, is generally expected to have all scripts in place that would commonly be expected. This has been formally manifested as a virtual package named build-essential:

$ sudo apt-get install build-essential

Building Debian packages also requires that all package-specific build dependencies are installed, as described in the section Satisfying Build Dependencies.

Как только эти предварительные условия соблюдены, сборка пакетов Debian состоит из двух шагов.

Первым шагом является создание скриптов пакета Debian и метаданных из репозитория git, путем запуска:

$ cd linuxcnc-dev
$ ./debian/configure
Note

Скриптdebian/configure отличается от скрипта src/configure!

Скрипт debian/configure принимает аргументы в зависимости от платформы, на которой/для которой вы строите, см. раздел debian/configure arguments section. По умолчанию LinuxCNC работает в пользовательском пространстве ("uspace"), ожидая, что ядро preempt_rt минимизирует задержки.

После конфигурации скриптов и метаданных пакета Debian соберите пакет, запустив dpkg-buildpackage:

$ dpkg-buildpackage -b -uc
Note

dpkg-buildpackage needs to run from the linuxcnc-source-dir directory, not from linuxcnc-source-dir/debian.
dpkg-buildpackage takes an optional argument ``-j``N (where N is a number). This enables to run multiple jobs simultaneously.

4.2.1. LinuxCNC’s debian/configure arguments

The LinuxCNC source tree has a debian directory with all the info about how the Debian package shall be built, but some key files within are only distributed as templates. The debian/configure script readies those build instructions for the regular Debian packaging utilities and must thus be run prior to dpkg-checkbuilddeps or dpkg-buildpackage.

The debian/configure script takes a single argument which specifies the underlying realtime or non-realtime platform to build for. The regular values for this argument are:

no-docs

Пропустить сборку документации.

uspace

Настройте пакет Debian для режима Preempt-RT в реальном времени или для режима не в реальном времени (эти два варианта совместимы).

noauto
rtai
xenomai

Обычно списки ОСРВ для поддержки uspace realtime определяются автоматически. Однако, если вы хотите, вы можете указать одну или несколько из них после uspace, чтобы включить поддержку этих ОСРВ. Чтобы отключить автоопределение, укажите noauto.

Если вам нужен только традиционный «модуль ядра» RTAI в реальном времени, используйте вместо этого -r или $KERNEL_VERSION.

rtai=<package name>

If the development package for RTAI, lxrt, does not start with "rtai-modules", or if the first such package listed by apt-cache search is not the desired one, then explicitly specify the package name.

-r

Настройте пакет Debian для работающего в данный момент ядра RTAI. Чтобы это работало, на вашей сборочной машине должно быть запущено ядро RTAI!

$KERNEL_VERSION

Configure the Debian package for the specified RTAI kernel version (for example "3.4.9-rtai-686-pae"). The matching kernel headers Debian package must be installed on your build machine, e.g. "linux-headers-3.4.9-rtai-686-pae". Note that you can build LinuxCNC in this configuration, but if you are not running the matching RTAI kernel you will not be able to run LinuxCNC, including the test suite.

4.2.2. Удовлетворение зависимостей сборки

На платформах на основе Debian мы предоставляем метаданные о пакетах , которые знают, какие внешние программные пакеты необходимо установить для сборки LinuxCNC. Это называется зависимостями сборки LinuxCNC. Они называются зависимостями сборки LinuxCNC, т.е. теми пакетами, которые должны быть доступны * the build succeeds and * the build can be built reproducibly.

You can use this meta-data to easily list the required packages missing from your build system. First, go to the source tree of LinuxCNC and initiate its default self-configuration, if not already performed:

$ cd linuxcnc-dev
$ ./debian/configure

This will prepare the file debian/control that contains lists of Debian packages to create with the runtime dependencies for those packages and for our cause also the build-dependencies for those to-be-created packages.

The most straightforward way to get all build-dependencies installed is to just execute (from the same directory):

sudo apt-get build-dep .

which will install all the dependencies required but available. The . is part of the command line, i.e. an instruction to retrieve the dependencies for the source tree at hand, not for dependencies of another package. This completes the installation of build-dependencies.

Оставшаяся часть этого раздела описывает полуручной подход. Список зависимостей в debian/control длинный, и сравнивать с ним текущее состояние уже установленных пакетов утомительно. В системах Debian есть программа под названием dpkg-checkbuilddeps, которая анализирует метаданные пакета и сравнивает пакеты, перечисленные как зависимости сборки, со списком установленных пакетов, а также сообщает вам, чего не хватает.

Сначала установите программу dpkg-checkbuilddeps, запустив:

$ sudo apt-get install dpkg-dev

This generates the file debian/control in a user-readable yaml-format which lists the build-dependencies close to the top. You can use this meta-data to easily list the required packages missing from your build system. You may decide to manually inspecting those files if you have a good understanding what is already installed.

Alternatively, Debian systems provide a program called dpkg-checkbuilddeps that parses the package meta-data and compares the packages listed as build dependencies against the list of installed packages, and tells you what’s missing. Also, dpkg-buildpackage would inform you about what is missing, and it should be fine. However, it reports missing build-deps only after patches in debian/patches are applied (if any). If you are new to Linux and git version management, a clean start may be preferable to avoid complications.

The dpkg-checkbuilddeps (also from the dpkg-dev package that is installed as part of the build-essential dependencies) program can be asked to do its job (note that it needs to run from the linuxcnc-source-dir directory, not from linuxcnc-source-dir/debian):

$ dpkg-checkbuilddeps

It will emit a list of packages that are required to build LinuxCNC on your system but are not installed, yet. You can now install missing build-dependencies

manually

Install them all with sudo apt-get install, followed by the package names. You can rerun dpkg-checkbuilddeps any time you want, to list any missing packages, which has no effect on the source tree.

automated

Run sudo apt build-dep . .

If in doubt about what a particular package of a build-dep may be providing, check out the package’s description with ``apt-cache show`` packagename.

4.2.3. Options for dpkg-buildpackage

For a typical Debian package to build, you would run dpkg-buildpackage without any arguments. As introduced above, the command has two extra options passed to it. Like for all good Linux tools, the man page has all the details with man dpkg-buildpackage.

-uc

Do not sign the resulting binaries. You would want to sign your packages with a GPG key of yours only if you would wanted to distribute them to others. Having that option not set and then failing to sign the package would not affect the .deb file.

-b

Only compiles the architecture-dependent packages (like the linuxcnc binaries and GUIs). This is very helpful to avoid compiling what is hardware-independent, which for LinuxCNC is the documentation. That documentation is available online anyway.

If you happen to run into difficulties while compiling, check the LinuxCNC forum online. Currently emerging is the support for the DEB_BUILD_OPTIONS environment variable. Set it to

nodocs

to skip building the documentation, preferably instead use the -B flag to dpkg-buildpackage.

nocheck

to skip self-tests of the LinuxCNC build process. This saves some time and reduces the demand for a few software packages that may not be available for your system, i.e. the xvfb in particular. You should not set this option for some extra confidence in your build to perform as expected unless running into difficulties with the dependencies.

An environment variable can be set together with the execution of the command, e.g.

DEB_BUILD_OPTIONS=nocheck dpkg-buildpackage -uc -B

would combine all the options introduced in this section.

4.2.4. Installing self-built Debian packages

A Debian package can be recognised by its .deb extension. The tool installing it, dpkg is part of every Debian installation. The .deb files created by dpkg-buildpackage are found in the directoy above the linuxcnc-source-dir, i.e. in ... To see what files are provided in a package, run

dpkg -c ../linuxcnc-uspace*.deb

The version of LinuxCNC will be part of the file name, which is meant to be matched by the asterisk. There may be too many files listed to fit on your screen. If you cannot scroll up in your terminal then add | more to that command to have its output passed through a so-called "pager". Quit with "q".

To install the packages, run

sudo dpkg -i ../linuxcnc*.deb

5. Setting up the environment

This section describes the special steps needed to set up a machine to run the LinuxCNC programs, including the tests.

5.1. Increase the locked memory limit

LinuxCNC tries to improve its realtime latency by locking the memory it uses into RAM. It does this in order to prevent the operating system from swapping LinuxCNC out to disk, which would have bad effects on latency. Normally, locking memory into RAM is frowned upon, and the operating system places a strict limit on how much memory a user is allowed to have locked.

When using the Preempt-RT realtime platform LinuxCNC runs with enough privilege to raise its memory lock limit itself. When using the RTAI realtime platform it does not have enough privilege, and the user must raise the memory lock limit.

If LinuxCNC displays the following message on startup, the problem is your system’s configured limit on locked memory:

RTAPI: ERROR: failed to map shmem
RTAPI: Locked memory limit is 32KiB, recommended at least 20480KiB.

To fix this problem, add a file named /etc/security/limits.d/linuxcnc.conf (as root) with your favorite text editor (e.g., sudo gedit /etc/security/limits.d/linuxcnc.conf). The file should contain the following line:

* - memlock 20480

Log out and log back in to make the changes take effect. Verify that the memory lock limit is raised using the following command:

$ ulimit -l

6. Сборка на Gentoo

Building on Gentoo is possible, but not supported. Be sure you are running a desktop profile. This project uses the Tk Widget Set, asciidoc, and has some other dependencies. They should be installed as root:

~ # euse -E tk imagequant
~ # emerge -uDNa world
~ # emerge -a dev-libs/libmodbus dev-lang/tk dev-tcltk/bwidget dev-tcltk/tclx
~ # emerge -a dev-python/pygobject dev-python/pyopengl dev-python/numpy
~ # emerge -a app-text/asciidoc app-shells/bash-completion

You can switch back to being a normal user for most of the rest of the install. As that user, create a virtual environment for pip, then install the pip packages:

~/src $ python -m venv   --system-site-packages ~/src/venv
~/src $ . ~/src/venv/bin/activate
(venv) ~/src $ pip install yapps2
(venv) ~/src $

Then you can contrinue as normally:

(venv) ~/src $ git clone https://github.com/LinuxCNC/linuxcnc.git
(venv) ~/src $ cd linuxcnc
(venv) ~/src $ cd src
(venv) ~/src $ ./autogen.sh
(venv) ~/src $ ./configure --enable-non-distributable=yes
(venv) ~/src $ make

There is no need to run "make suid", just make sure your user is in the "dialout" group. To start linuxcnc, you must be in the Python Virtual Environment, and set up the linuxcnc environment:

~ $ . ~/src/venv/bin/activate
(venv) ~ $ . ~/src/linuxcnc/scripts/rip-environment
(venv) ~ $ ~/src/linuxcnc $ scripts/linuxcnc

7. Options for checking out the git repo

The Quick Start instructions at the top of this document clone our git repo at https://github.com/LinuxCNC/linuxcnc.git. This is the quickest, easiest way to get started. However, there are other options to consider.

7.1. Fork us on Github

The LinuxCNC project git repo is at https://github.com/LinuxCNC/linuxcnc. github is a popular git hosting service and code sharing website. You can easily (and for no cost) create a fork of our git repo at github, and use that to track and publish your changes.

After creating your own github fork of LinuxCNC, clone it to your development machine and proceed with your hacking as usual.

We of the LinuxCNC project hope that you will share your changes with us, so that the community can benefit from your work. Github makes this sharing very easy: after you polish your changes and push them to your github fork, send us a Pull Request.