Installing source code on linux

How to Compile and Install Software from Source Code on Linux

While yum, apt-get, rpm are very handy to install a package that is already compiled, you still might encounter some situations where you have to install a software from source code. This article explains on a very high level how to compile and install a software from source code.

Download the Source Code Package and Unpack it

The source code for software on Linux comes in the form of compressed tar files, which typically have either .tar.gz or .tar.bz2 extensions. The tools that are used for packing the source code into these tar balls are ‘tar’ (used for combining multiple files into one), ‘gzip’ or bzip2 (used for compression). To fetch the source code tarball for a particular software you need to know the URL to the tarball. Once you have the download link, use ‘wget’ to fetch the tarball from command line.

The above command will download the tarball into the current directory. wget command is very flexible and has lot of options. To learn more about wget, refer to the 15 wget examples. Next you needs to unpack the tarball in order to get access to the source code and other files. Depending on the extension, use one of the following commands:

tar command is very flexible and has lot of options. To learn more about tar, refer to the 10 tar examples.

Read Install Documentation

Once the software source code is downloaded and extracted, the very first thing that one should do is to go through the documentation. This may sound boring to most of us but this is a very important step as doing this step thoroughly would save you from most of the future problems. The documentation provides information about the software, changes since last version, links to more documentation, information regrading the author of the software, steps for compilation and installation of software etc. So we can see that lots of valuable information is present in the documentation. This whole information is broadly divided into two files : ‘Readme’ and ‘Install’. While ‘Install’ covers all the information required for compilation and installation, all the other information is covered in the ‘Readme’ file. Please note that the name of file and it case may vary.

Читайте также:  Astra linux оффлайн репозиторий

Configuration

Once the above step is over then we can assume that we have sufficient theoretical knowledge about this software and now we can move forward and configure the environment for compiling and installing the software on our system. Most of the packages come along with a configuration script that can be used for configuring the environment. The file name for configuration file is mostly ‘configure’. This script usually accepts parameters that can be used to control some features of this software. Also this script makes sure that all the tools required for compilation are present in the system. To learn about the options provided by a specific configuration file, run the following command:

The above command will check and/or create the build environment and if everything goes fine then it produces a file called ‘makefile’. The file ‘makefile’ is used in the compilation of the software.

Compilation

The above command will compile all the source code related to the software. If compilation encounters some problem then error is thrown on the console.

Installation

Once the compilation is done successfully then all the required binaries are created. Now is the time to install these binaries in the standard paths so that they can be invoked from anywhere in the system. To do this run the following command :

While compiling and installing open source software from source, there could be some issues/errors that may come up. Lets look at a few of those here:

  • Missing shared library: Sometimes when you run the program you just installed, you get an error related to some .so that your program is not able to find. Firstly, .so are synonymous to the DLLs we have in windows. These are shared libraries that are required by the program. Secondly, these type of errors erupt when your program is installed in some non-standard path or the shared library is actually not present in your system. For the first case, you need to tell the shell environment the path at which these new shared libraries are installed. This can be done by using the ‘ldconfig’ command or by modifying the LD_LIBRARY_PATH variable.
  • Broken source code: No matter how much pain you take by going through all the documentation and covering all the steps building the software but if the source code gives some compilation error then it very much means that the software has broken source code. Nothing much can be done in this case except referring this problem back to the author of this software. Meanwhile, if you think you can you may debug the errors and see if these are trivial errors that can be fixed (like syntactical errors).
  • No configure script: Though rare, but sometimes you’ll find that there is no configuration script present in the source code directory. If this happens that does not mean that you are stuck. In this case all you need is to go through the documentation in detail and there you will definitely find some information regarding configuration of environment for compiling and installation of software.
Читайте также:  Узнать ip cmd linux

If you enjoyed this article, you might also like..

Comments on this entry are closed.

Actually, it’s more useful to use ‘checkinstall’ instead of ‘make install’. This command will create a package for your system out of the sources and install it via native methods. It’ll make package update and removal easier.

Thank you.
Due to memory loss (strokes) issues I need to have many “cheat sheets.”
This is a valuable article for me to add to my collection.

Источник

Компиляция и установка программ из исходников

Не редко необходимые пакеты можно найти только в виде исходных текстов, в данной статье описывается метод установки пакета из исходных текстов.

Распаковка

Программы обычно распространяются в упакованных архивах, это файлы с расширениями

Нужно понимать отличие между архиватором и упаковщиком.

Для архивации директорий и файлов используется программа tar; результатом её работы является файл с расширением .tar. Грубо говоря, это копия файловой системы — директорий и файлов с их атрибутами и правами доступа, помещённая в один файл.

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

Программа tar умеет распаковывать, поэтому не нужно вызывать gunzip, а можно просто указать программе tar, что файл нужно cначала распаковать. Например, команда

tar -xvf some_app_name>.tar.gz

сразу распакует и разархивирует. Отличие файлов с расширениями

лишь в том, что использовались разные упаковщики, программа tar определяет метод сжатия автоматически и дополнительных опций в данном случае не требуется.

После распаковки необходимо перейти в полученный каталог, все описываемые ниже команды выполняются в каталоге с исходными текстами пакета.

Сборка пакета

Для сборки программ в GNU/Linux используется (в основном) программа make, которая запускает инструкции из Makefile, но поскольку дистрибутивов GNU/Linux много, и они все разные, то для того чтобы собрать программу, нужно для каждого дистрибутива отдельно прописывать пути,где какие лежат библиотеки и заголовочные файлы. Программисты не могут изучать каждый дистрибутив и для каждого отдельно создавать Makefile. Поэтому придумали конфигураторы, которые «изучают» систему, и в соответствии с полученными знаниями создают Makefile. Но на конфигураторе они не остановились и придумали конфигураторы конфигураторов =)…на этом они остановились :-)

Для сборки нам нужны компиляторы: они прописаны в зависимостях пакета build-essential, так что достаточно установить его со всеми зависимостями. Ещё нужны autoconf и automake.

Итак, чтобы собрать что-то из исходников, нужно сначала собрать конфигуратор; как собрать конфигуратор, описано в файле configure.in. Для сборки конфигуратора необходимо выполнить

Если таких скриптов в архиве не оказалось, то можно выполнить последовательно следующие команды:

aclocal autoheader automake --gnu --add-missing --copy --foreign autoconf -f -Wall

Все эти команды используют файл configure.in. После выполнения этих команд создастся файл configure. После этого необходимо запустить конфигуратор для проверки наличия всех зависимостей, а также установки дополнительных опций сборки (если возможно) и просмотра результата установки (опционально- может не быть)

Конфигуратор построит Makefile основываясь на полученных знаниях и файле makefile.am. Можно передать конфигуратору опции, предусмотренные в исходниках программы, которые позволяют включать/отключать те или иные возможности программы, обычно узнать о них можно командой

Также есть набор стандартных опций, вроде

, которая указывает, какой каталог использовать для установки. Для Ubuntu обычно

БЕЗ слеша в конце! Теперь можно запустить процесс сборки самой программы командой

Для сборки достаточно привелегий обычного пользователя. Окончанием сборки можно считать момент, когда команды в консоли перестанут «беспорядочно» выполняться и не будет слова error. Теперь всё скомпилировано и готово для установки.

Установка

Усилия потраченные на Правильную установку в последствии с лихвой окупятся в случае удаления или обновления устанавливаемого программного обеспечения.

Правильная установка(Вариант №1)

Установка при помощи утилиты checkinstall. Для установки выполните

sudo apt-get install checkinstall

Минус данного способа: checkinstall понимает не все исходники, поскольку автор программы может написать особые скрипты по установке и checkinstall их не поймёт.

Для создания и установки deb-пакета необходимо выполнить

Правильная установка(Вариант №2)

Быстрое создание deb-пакета «вручную».

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

fakeroot make install DESTDIR=`pwd`/tempinstall

Создадим в «корне пакета» директорию DEBIAN и сложим в DEBIAN/conffiles список всех файлов, которые должны попасть в /etc:

сd tempinstall mkdir DEBIAN find etc | sed "s/^/\//" > DEBIAN/conffiles
Package: имя_пакета Version: 1.2.3 Architecture: amd64/i386/armel/all Maintainer: Можете вписать своё имя, можете дребедень, но если оставить пустым, то dpkg будет ругаться Depends: Тут можно вписать список пакетов через запятую. Priority: optional Description: Тоже надо что-нибудь вписать, чтобы не кидало предупреждения
sudo dpkg -i tempinstall.deb

Источник

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