Compile on Linux/ru

Обзор
В последних дистрибутивах Linux, FreeCAD, как правило, собирается легко, поскольку все зависимости обычно предоставляются менеджером пакетов. В основном сборка включает 3 этапа:
 * 1) Получение исходного кода FreeCAD.
 * 2) Получение зависимостей, или пакетов, от которых зависит FreeCAD
 * 3) Настройка с помощью  и компиляция с помощью.

Ниже вы найдете подробное описание процесса сборки, некоторых скриптов компиляции и особенностей, с которыми Вы можете столкнуться. Если вы найдете ошибки, устаревшие сведения (дистрибутивы Linux меняются быстро), или если вы используете дистрибутив, которого нет в списке, обсудите вопрос на форуме, и помогите нам исправить это.



Git
Лучший способ получить код это клонировать только-для-чтения репозиторий Git. Для этого вам потребуется программа, которую легко установить в большинстве дистрибутивов Linux, или получить на официальном веб-сайте.

Эта команда копирует последнюю версию исходного кода FreeCAD в папку.

Для получения дополнительной информации об использовании Git и внесении кода в проект, смотрите Работа с исходными кодами.

Архив с исходным кодом
Иначе, Вы можете загрузить исходники как архив, файл или, и распаковать его в желаемый каталог.

Установка зависимостей (Dependencies)
Для компиляции FreeCAD необходимо установить требуемые зависимости (dependencies), упомянутые в сторонних библиотеках; пакеты, содержащие эти зависимости, перечислены ниже для различных дистрибутивов Linux. Обратите внимание, что имена и доступность библиотек будут зависеть от вашего конкретного дистрибутива; если ваш дистрибутив устарел, некоторые пакеты могут быть недоступны или иметь другое имя. В этом случае посмотрите раздел 🡇 старые и нестандартные дистрибутивы расположенный ниже.

Как только у вас будут установлены все зависимости, перейдите к compile FreeCAD.

Please note that FreeCAD's source code is around 500 MB in size; it may be three times as big if you clone the Git repository with its entire modification history. Getting all dependencies may require downloading 500 MB or more of new files; when these files are unpacked they may require 1500 MB or more in space. Also beware that the compilation process may generate up to 1500 MB of additional files as the system copies and modifies the entire source code. Therefore, be sure you have enough free space in your hard drive, at least 4 GB, when attempting compilation.

Debian и Ubuntu
В системах основанных на Debian (Debian, Ubuntu, Mint, и т.п.) довольно легко установить все необходимые зависимости. Большинство библиотек доступны через или менеджер пакетов Synaptic.

Если вы уже установили FreeCAD из официальных репозиториев, вы можете установить зависимости (dependencies) для его сборки с помощью этой единственной строки кода в терминале:

Однако, если версия FreeCAD в репозиториях старая, зависимости (dependencies) могут быть уже устаревшими для компиляции последней версии FreeCAD. Поэтому, пожалуйста, убедитесь, что вы установили следующие пакеты.

Эти пакеты необходимы для успешной компиляции в целом:
 * , устанавливает компиляторы C и C++, библиотеки разработки C и утилиту.
 * , необходимый инструмент для настройки исходников FreeCAD. Вы также можете установить и  чтобы иметь графический интерфейс для данной утилиты.
 * , необходимые инструменты для создания shared библиотек.
 * , стандартная утилита базовой отчетности обычно уже установлена в системе Debian и позволяет программно различать чистую установку Debian или ее вариант, такой как Ubuntu или Linux Mint. Не удаляйте этот пакет, так как от него могут зависеть многие другие системные пакеты.

При компиляции FreeCAD используется язык Python, и он также используется в runtime в качестве языка сценариев. Если вы используете дистрибутив на основе Debian, интерпретатор Python как правило уже установлен в нем.
 * , это инструмент, который создает интерфейсы между кодом C++ и Python.
 * , это инструмент, который создает интерфейсы между кодом C++ и Python.

Please check that you have Python 3 installed. Python 2 was obsoleted in 2019, so new development in FreeCAD is not tested with this version of the language.

Boost библиотеки должны быть обязательно установлены:



The Coin libraries need to be installed:
 * , for Debian Jessie, Stretch, Ubuntu 16.04 to 18.10, or
 * , for Debian Buster, Ubuntu 19.04 and newer, as well as for Ubuntu 18.04/18.10 with the freecad-stable/freecad-daily PPAs added to your software sources.

Несколько библиотек, которые занимаются вычислениями, триангулированными поверхностями, сортировкой, мешами (meshes), компьютерным зрением, картографическими проекциями, 3D-визуализацией, оконной системой X11, парсингом XML и чтением Zip-файлов:


 * or
 * or
 * or
 * or
 * or
 * or
 * or
 * or

Python 2 и Qt4
Python 2 и Qt4 уже устарели и не рекомендуются к применению. Начиная с версии 0.20, в FreeCAD они больше не поддерживаются.

При компиляции FreeCAD в Debian Jessie, Stretch, Ubuntu 16.04, используйте Python 2 и Qt4, установив следующие зависимости:



Python 3 и Qt5
При компиляции FreeCAD в Debian Buster, Ubuntu 19.04 и выше, а также Ubuntu 18.04/18.10 с freecad-stable/freecad-daily PPAs добавленным в ваш исходный код, установите следующие зависимости.


 * (if compiling 0.20 on a machine that still has Qt4)
 * or
 * (if compiling 0.20 on a machine that still has Qt4)
 * or
 * or
 * or

Ядро OpenCascade
Ядро OpenCascade - это основная графическая библиотека для создания 3D-фигур. Она существует в виде официальной версии OCCT и виде версии для сообщества OCE. Версия для сообщества к применению больше не рекомендуется, так как она устарела.

For Debian Buster and Ubuntu 18.10 and newer, as well as Ubuntu 18.04 with the freecad-stable/freecad-daily PPAs added to your software sources, install the official packages.



For Debian Jessie, Stretch, Ubuntu 16.04 and newer, install the community edition packages.



You may install the libraries individually, or using asterisk expansion. Change for  if you want to install the community libraries.

Необязательные к установке пакеты
При желании вы также можете установить эти дополнительные пакеты:
 * , чтобы Coin поддерживал дополнительные форматы файлов изображений.
 * и (или  для старых систем), если вы хотите автоматический генерировать документацию к исходному коду.
 * , для поддержки устройств 3D ввода, таких как 3Dconnexion "Space Navigator" или "Space Pilot".
 * , если вы хотите зарегистрировать установленные файлы в диспетчере пакетов вашей системы, чтобы вы могли удалить их позже.

Single command for Python 3 and Qt5
Requires Pyside2 available in Debian buster and the freecad-stable/freecad-daily PPAs.

NOTE: On some versions of Ubuntu and some versions of Qt, you will get an error that python3-pyside2uic cannot be found -- on those systems you can safely omit it. On Ubuntu 20.04 you will need to add pyqt5-dev-tools. More information can be found in this forum discussion.

Single command for Python 2 and Qt4
This is not recommended for newer installations as both Python 2 and Qt4 are obsolete.

Ubuntu 16.04 users please see also the compilation discussion in the forum: Compile on Linux (Kubuntu): CMake can't find VTK.

Raspberry Pi
Follow the same steps as in Debian and Ubuntu.

There are problems reported when trying to compile in Raspbian with Python 3 and Qt5, but the combination Python 3 and Qt4 seems to work for older versions of FreeCAD.

For newer versions of FreeCAD the compilation with Py3/Qt5 is successful if the operating system installed is Ubuntu 20.04.

Due to different issues with Qt, in this version the normal PySide tools won't be found.

In this case, we can install the packages from PyQt and create symbolic links to the needed tools.

Now compilation may proceed.

The option to  should not be more than 3 because the Raspberry Pi has limited memory. It will take several hours to compile, so it is better to do it overnight.

More information, FreeCAD and Raspberry Pi 4.

Fedora
You need the following packages :


 * gcc-c++ (or possibly another C++ compiler?)
 * cmake
 * doxygen
 * swig
 * gettext
 * dos2unix
 * desktop-file-utils
 * libXmu-devel
 * freeimage-devel
 * mesa-libGLU-devel
 * OCE-devel
 * python
 * python-devel
 * python-pyside-devel
 * pyside-tools
 * boost-devel
 * tbb-devel
 * eigen3-devel
 * qt-devel
 * qt-webkit-devel
 * qt5-qtxmlpatterns
 * qt5-qttools-static
 * ode-devel
 * xerces-c
 * xerces-c-devel
 * opencv-devel
 * smesh-devel
 * Coin3
 * Coin3-devel

(Coin not to be confused with coin - a financial pkg. April 2021, Coin4 and Coin4-devel are available ) (if coin2 is the latest available for your version of Fedora, use packages from http://www.zultron.com/rpm-repo/)


 * SoQt-devel
 * freetype
 * freetype-devel
 * vtk
 * med
 * med-devel

And optionally :


 * libspnav-devel (для поддержки устройств 3Dconnexion, вроде Space Navigator или Space Pilot)
 * pivy ( https://bugzilla.redhat.com/show_bug.cgi?id=458975 Pivy не обязателен, но нужен для модуля Draft)

Gentoo
Простейший путь проверить, какие пакеты нужны для компиляции FreeCAD это проверить через portage:

emerge -pv freecad

Вы получите список дополнительных пакетов, которые следует установить на Вашей системе.

Если FreeCAD недоступен в portage, он доступен в оверлее waebbl. Система отслеживания ошибок на оверлее waebbl Github может помочь решить некоторые проблемы, с которыми вы можете столкнуться. Оверлей предоставляет  freecad-9999 , который вы можете выбрать для компиляции или просто использовать для получения зависимостей.

layman -a waebbl

Tumbleweed
The following commands will install the packages required for building FreeCAD with Qt5 and Python 3.

The following command will install Qt Creator and the GNU Project Debugger.

If any packages are missing, then you can check the Tumbleweed "FreeCAD.spec" file on the Open Build Service.

Also, check to see if there are any patches you need to apply (such as 0001-find-openmpi2-include-files.patch).

Leap
If there is a difference between the available packages on Tumbleweed and Leap, then you can read the Leap "FreeCAD.spec" file on the Open Build Service to determine the required packages.

See piano_jonas unofficial "Compile On openSUSE" guide.

Arch Linux
You will need the following libraries from the official repositories:


 * boost
 * curl
 * desktop-file-utils
 * glew
 * hicolor-icon-theme
 * jsoncpp
 * libspnav
 * opencascade
 * shiboken2
 * xerces-c
 * pyside2
 * python-matplotlib
 * python-netcdf4
 * qt5-svg
 * qt5-webkit
 * qt5-webengine
 * cmake
 * eigen
 * git
 * gcc-fortran
 * pyside2-tools
 * swig
 * qt5-tools
 * shared-mime-info
 * coin
 * python-pivy
 * med

Older and non-conventional distributions
On other distributions, we have very few feedback from users, so it might be harder to find the required packages.

Try first locating the required libraries mentioned in third party libraries in your package manager. Beware that some of them might have a slightly different package name; search for, but also , , , and similar. If that is not possible try compiling those libraries yourself.

FreeCAD requires the GNU g++ compiler version equal or above 3.0.0, as FreeCAD is mostly written in C++. During the compilation some Python scripts are executed, so the Python interpreter has to work properly. To avoid any linker problems it is also a good idea to have the library paths in the variable or in the  file. This is already done in modern Linux distributions, but may need to be set in older ones.

Pivy
Pivy (Python wrappers to Coin3d) is not needed to build FreeCAD or to start it, but it is needed as a runtime dependency by the Draft Workbench. If you are not going to use this workbench, you won't need Pivy. However, do notice that the Draft Workbench is used internally by other workbenches, like Arch and BIM, so Pivy needs to be installed to use these workbenches as well.

By November 2015 the obsolete version of Pivy included with the FreeCAD source code will no longer compile on many systems. This isn't a big problem as normally you should get Pivy from your distribution's package manager; if you cannot find Pivy, you may have to compile it yourself, see Pivy compilation instructions.

Debug symbols
In order to troubleshoot crashes in FreeCAD, it is useful to have the debug symbols of important dependency libraries such as Qt. For this, try installing the dependency packages that end with, , or similar, depending on your Linux distribution.

For Ubuntu, you may have to enable especial repositories to be able to see and install these debug packages with the package manager. See Debug Symbol Packages for more information.

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


 * 1) CMake checks that every needed program and library is present on your system, and generates a  that is configured for the second step. FreeCAD has several configuration options to choose from, but it comes with sensible defaults. Some alternatives are detailed below.
 * 2) The compilation itself, which is done with the program, which generates the FreeCAD executables.

Since FreeCAD is a large application, compiling the entire source code can take anywhere from 10 minutes to one hour, depending on your CPU and the number of CPU cores used for compilation.

You can build the code either in or out of the source directory. Out-of-source building is generally the best option.

Out-of-source build
Building in a separate folder is more convenient than building in the same directory where the source code is located as every time you update the source code CMake can intelligently determine which files have changed, and recompile only what is needed. This is very useful when testing different Git branches as you don't confuse the build system.

To build out-of-source, simply create a build directory,, distinct from your FreeCAD source folder, ; then from this build directory point to the right source folder. You can use or  instead of  in the instructions below as well. Once finishes configuring the environment, use  to start the actual compilation.

Note: if you are compiling the 0.19 release branch, you must explicitly specify that you are compiling with Qt5 and Python 3 -- replace the cMake command above with:

The option of  controls how many jobs (files) are compiled in parallel. The program prints the number of CPU cores in your system; by using it together with the  option you can choose to process as many files as you have cores, in order to speed up overall compilation of the program. In the example above, it will use all cores in your system except two; this will keep your computer responsive for other uses while compilation proceeds in the background. The FreeCAD executable will eventually appear in the directory. See also Compiling (speeding up) to improve compilation speed.

Сборка внутри древа исходников
In-source builds are fine if you want to compile a version of FreeCAD quickly, and don't intend to update the source code often. In this case, you can remove the compiled program and the source just by deleting a single folder.

Change to the source directory, and point to the present directory (denoted by a single point):

Исполняемый файл FreeCAD будет находиться в каталоге

Как восстановить папку с исходными кодами
If you accidentally performed a compilation inside the source code directory, or added strange files, and would like to restore the contents to only the original source code, you can perform the following steps.

Первая строка очищает файл. Это гарантирует, что следующие команды clean и reset будут влиять на все в каталоге и не будут игнорировать элементы, соответствующие выражениям в. Вторая строка удаляет все файлы и каталоги, которые не отслеживаются репозиторием git, затем последняя команда сбрасывает все изменения в отслеживаемых файлах, включая первую команду, которая очистила файл.

If you do not clear the source directory, subsequent runs of may not capture new options to the system if the code changes.

Конфигурирование
By passing different options to, you can change how FreeCAD is compiled. The syntax is as follows.

Where is the directory that contains the source code. The may be omitted in most cases. The space after the option may also be omitted.

For example, to avoid building the FEM Workbench:

All possible variables are listed in the file, located in the  directory. In this file, search for the word to get to the variables that can be set, and see their default values.


 * 1) =================   All the options for the build process    =================
 * 1) =================   All the options for the build process    =================

option(BUILD_FORCE_DIRECTORY "The build directory must be different to the source directory." OFF) option(BUILD_GUI "Build FreeCAD Gui. Otherwise you have only the command line and the Python import module." ON) option(FREECAD_USE_EXTERNAL_ZIPIOS "Use system installed zipios++ instead of the bundled." OFF) option(FREECAD_USE_EXTERNAL_SMESH "Use system installed smesh instead of the bundled." OFF) ...

Alternatively, use the command to list the current configuration, and thus all variables that can be changed. You may also install and use to launch a graphical interface showing all the variables that can be modified. In the next sections we list some of the more relevant options that you may want to use.

Для сборки под отладку
Create a build to troubleshoot crashes in FreeCAD. Beware that with this build the Sketcher becomes very slow with complex sketches.

Для рабочей сборки
Create a build to test code that doesn't crash. A build will run much faster than a  build.

Building against Python 3 and Qt5
By default, FreeCAD 0.19 and earlier build for Python 2 and Qt4. Since these two packages are obsolete, it is better to build for Python 3 and Qt5. Support for Python 2 and Qt4 has been removed in FreeCAD 0.20 and it is not necessary to explicitly enable Qt5 and Python 3 if compiling the latest development versions.

In a modern Linux distribution you only need to provide two variables specifying the use of Qt5, and the path to the Python interpreter.

Для 0.19:

Для 0.20_dev:

Note that when switching between 0.19 and the 0.20 builds, it may be necessary to delete CMakeCache.txt prior to running cmake.

Сборка с применением особых версий Python
If the default executable in your system is a symbolic link to Python 2,  will try to configure FreeCAD for this version. You can choose another version of Python by giving the path to a specific executable:

If that doesn't work, you may have to define additional variables pointing to the desired Python libraries and include directories:

It is possible to have several independent versions of Python in the same system, so the locations and version numbers of your Python files will depend on your particular Linux distribution. Use to display the version of Python that you are using currently; only the first two numbers are necessary; for example, if the result is, you need to specify the directories that relate to the 3.6 version. If you don't know the right directories, try searching for them with the command.

You may use in a terminal to determine the  directory, or  for Debian systems.

Building with Qt Creator against Python 3 and Qt5
1. Launch Qt Creator.

2. Click on.

3. Navigate to the directory where the source code is,, and choose the topmost file.

4. By selecting the file, it will automatically run on it, but it may fail if the appropriate options aren't correctly set.

5. Go to. Set the appropriate build directory,.

6. Set the appropriate variables in the Key-Value dialog, of types and.

7. If the variables do not load the project correctly, you may have to go to. Then press, and add the appropriate configuration as described above. You may have to add more variables about the Python paths, if the system Python is not found.

7.1. Press, then.

7.2. Make sure the rest of the options are correctly set, for example, should be a present version installed in the system, like.

Press, then to close the configuration.

The program should run automatically again, and it should fill the entire Key-Value dialog with all the variables that can be configured.

8. Go to and choose  to compile the graphical version of FreeCAD, or  to compile only the command line version.

9. Finally, go to the menu. If this is a new compilation, it should take several minutes, inclusive hours, depending on the number of processors that you have available.

Плагин Qt designer
Если Вы хотите разрабатывать Qt-код для FreeCAD, Вам понадобится плагин к Qt Designer, который обеспечивает все пользовательские виджеты FreeCAD.

Go into an auxiliary directory of the source code, the run with the indicated project file to create a ; then run  to compile the plugin.

If you are compiling for Qt5, make sure the binary is the one for this version, so that the resulting  contains the necessary information for Qt5.

where is the directory that stores Qt binary libraries, for example,.

The library created is, which needs to be copied to.

Внешний или встроенный Pivy
Previously, a version of Pivy was included in the source code of FreeCAD (internal). If you wanted to use your system's copy of Pivy (external), you needed to use.

Using external Pivy became the default during development of FreeCAD 0.16, therefore this option does not need to be set manually anymore.

Документирование посредством Doxygen
If you have Doxygen installed you can build the source code documentation. See source documentation for instructions.

Дополнительная документация
The source code of FreeCAD is very extensive, and with CMake it's possible to configure many options. Learning to use CMake fully may be useful to choose the right options for your particular needs.
 * CMake Reference Documentation by Kitware.
 * How to Build a CMake-Based Project (blog) by Preshing on programming.
 * Learn CMake's Scripting Language in 15 Minutes (blog) by Preshing on programming.

Создание пакета debian
Если Вы планируете собрать пакет Debian вне исходников, вам следует сначала установить следующие пакеты:

Перейдите в папку FreeCAD и выполните

Когда пакет построен, Вы можете использовать для проверки, содержит ли пакет ошибки

Обновление исходного кода
The CMake system allows you to intelligently update the source code, and only recompile what has changed, making subsequent compilations faster.

Move to the location where the FreeCAD source code was first downloaded, and pull the new code:

Then move into the build directory where the code was compiled initially, and run specifying the present directory (denoted by a dot); then trigger the re-compilation with.

Примечание для 64-битных систем
При компиляции FreeCAD на 64-бит известна проблема с 64-битным пакетом OpenCASCADE. Чтобы FreeCAD правильно заработал, Вам нужно запустить скрипт и установить дополнительно :

For Debian based systems this option is not needed when using the pre-built OpenCASCADE packages because these ones set the proper internally.

Скрипты автоматической компиляции
Это всё, что Вам нужно для полной компиляции FreeCAD. Это односкриптовое решение, работающее на свежеустановленном дистрибутиве. Команда запросит пароль root для установки пакетов новых онлайновых репозиториев. Эти скрипты должны запускаться на 32- и 64-битных версиях. Они написаны для разных версий, но, скорее всего, будут работать для позднейший версий с небольшими изменениями или без них.

If you have such a script for your preferred distribution, please discuss it on the FreeCAD forum so we can incorporate it.

Ubuntu
Эти скрипты обеспечивают надёжный путь для установки верного набора зависимостей, требуемых для сборки и запуска FreeCAD в Ubuntu. Они используют репозитории PPA Ubuntu FreeCAD, и должны работать на любой версии Ubuntu, для которой есть целевой PPA. PPA на freecad-daily нацелен на последнюю версию Ubuntu, а 'стабильный' PPA нацелен на официально поддерживаемые версии Ubuntu.

This script installs the daily compiled snapshot of FreeCAD and its dependencies. It adds the daily repository, gets the dependencies to build this version, and installs the required packages. Afterwards it proceeds to pull the source code into a particular directory, creates a build directory and changes into it, configures the compilation environment with, and finally builds the entire program with. Save the script to a file, make it executable, and run it, but don't use ; superuser privileges will be asked only for selected commands.

If you wish, you can uninstall the pre-compiled version of FreeCAD while leaving the dependencies in place, however, leaving this package installed will allow the package manager to keep its dependencies up to date as well; this is mostly useful if you intend to follow the development of FreeCAD, and constantly update and compile the sources from the Git repository.

The previous script assumes that you want to compile the latest version of FreeCAD, so you are using the "daily" repository to get the dependencies. However, you can instead get the build dependencies of the "stable" version for your current Ubuntu release. If this is the case, replace the top part of the previous script with the following instructions. For Ubuntu 12.04, omit from the command.

Once you install the package from the  repository, it will supersede the FreeCAD executable that is available from the Universe Ubuntu repository. The executable will be named simply, and not.

openSUSE
No external Repositories are needed to compile FreeCAD. However, there is an imcompatability with python3-devel which needs to be removed. FreeCAD can be compiled from GIT

Since you are using git, next time you wish to compile you do not have to clone everything, just pull from git and compile once more

Fedora 27/28/29
Posted by user [PrzemoF] in the forum.

{ echo "~/$MAIN_DIR already exist. Quitting.."; exit; } cd $MAIN_DIR git clone https://github.com/FreeCAD/FreeCAD.git mkdir $BUILD_DIR

Arch using AUR
Arch User Repository (AUR) is a collection user made recipes to build packages which are not officially supported by distribution maintainers / community. They are usually safe. You can see who maintain the package and for how long he did. It is recommended to check construction files. Also non open source software are available in this area even if maintained by the official owning company.

Prerequisite : git

Steps :
 * 1) Open a terminal. Optionally create a directory eg. . Optionally change directory eg..
 * 2) Clone the AUR repository :
 * 3) Enter AUR repository folder :
 * 4) Compile using Arch makepkg : . The -s or --syncdeps flag will also install required dependencies.
 * 5) Install created package : or double click on the pkgname-pkgver.pkg.tar.xz inside your file browser.

To update FreeCAD to latest build just repeat from step 3. Update AUR repo when there is some breaking change in the recipe or new features using inside the folder.