Linux build configure file

How do I create a configure script?

This may sound like a very generic question but here it goes. I have a requirement to create a configure script for my application, the result of this configure would be a generated makefile (basic configure , make , make install ). My question is, where do I start in building this? Is there an example I can follow?

4 Answers 4

To create the standard «configure» script you need GNU autoconf. You may need GNU automake and libtool too.

There are tons of documentation and howtos. Google for something like «autoconf automake howto». The good documentation is in the official manual pages:

  • Autoconf: http://www.gnu.org/software/autoconf/
  • Automake: http://www.gnu.org/software/automake/automake.html
  • Libtool: http://www.gnu.org/software/libtool/libtool.html

Autoconf will create your configure script starting from the «configure.ac» file. The «Makefile.am» file will instruct automake on how to create your makefile by the configure string. Libtool is needed to simplify libraries handling around your code.

You can start creating a configure.ac file by hand or you may use the «autoscan» helper that may help you to create something semi-automatic for you.

Then, when you are ready, this one will do the magic:

GNU docs imply there could be other configure script tools : gnu.org/prep/standards/html_node/Makefile-Conventions.html , Are there any such other tools (apart from manual of course)?

Sometimes a software product will ship with no configure script. Look for an autogen.sh script. it will probably run:

aclocal || die "aclocal failed" automake --add-missing --force-missing --copy --foreign || die "automake failed" autoreconf || die "autoreconf failed" 

All of these answers are about autoconf which is a GNU tool. However, configure shell scripts have been in UNIX long before GNU and can be created by hand or in other ways.

What does configure do?

configure is a just shell script. It’s job is to generate a list of configuration variables that the makefile needs to build the software on that particular system. For example, it might determine the linker flags and header search paths needed to include a specific library.

configure can also accept options from the user, for example to control whether to build in debug or release mode.

Typically configure writes these variables to a file called config.mk which is included by the makefile . It may also generate a header config.h with some preprocessor defines. Note that configure is just a helpful automation for producing this. The user can always just hand edit config.mk themselves (especially on obscure systems).

Читайте также:  Просмотр запущенных процессов linux команда

How does configure detect features?

configure uses a variety of techniques to locate dependencies and detect system or hardware features. The least stable (but sometimes necessary way) is to check the uname to detect and operating system. One useful tool is pkg-config which can tell you where to find various installed libraries.

Lastly, configure scripts can always generate small snippets of code, and then trying to compile them to see if a feature is available.

Joe Nelson has a great article with examples for each of these ideas.

Should I write my own configure or use autoconf?

Most programs only have 1 or 2 small things they need to detect to get working. I think it makes sense to write a configure script in these cases, rather than try to figure out corner cases of the massive piece of software that is autotools. If you product a simple config.mk it can always be fixed by hand, and users of various systems will be helpful in getting your configure to work correctly.

For more complex dependencies, autoconf is probably useful.

To be fair to all parties, let’s relate the argument made in autoconf ‘s documentation:

The primary goal of Autoconf is making the user’s life easier; making the maintainer’s life easier is only a secondary goal.

Autoconf is highly successful at its goal—most complaints to the Autoconf list are about difficulties in writing Autoconf input, and not in the behavior of the resulting configure. Even packages that don’t use Autoconf will generally provide a configure script, and the most common complaint about these alternative home-grown scripts is that they fail to meet one or more of the GNU Coding Standards (see Configuration in The GNU Coding Standards) that users have come to expect from Autoconf-generated configure scripts.

  • your configure might not have all the commands some users expect.
  • You might detect features incorrectly or using incorrect assumptions for example if macOS < use mac commands >else < use linux commands >, instead of if gnuTools < use gnu commands >else < use bsd/posix commands >.

You will have to determine whether that’s important to you.

Источник

Чарующая магия configure, make и make install

Это небольшая заметка для начинающих линуксоидов, о том что же означают эти три замечательные команды и для чего одни нужны. Начнём, как говорится, с начала. Большинство программ перед использованием надо скомпилировать, то есть преобразовать из текста понятного человеку в набор единиц и нулей, понятных компьютеру. Процесс условно разделён на три этапа: конфигурирование (configure), сборка (make) и установка (make install). Подробности под катом 🙂

Читайте также:  Загрузка linux menu lst

./configure

Данная команда выполняет поиск необходимых для компиляции библиотек и заголовочных файлов (это для программ частично или полностью написанных на C/C++ и подобных языков), а так же настройку особых параметров или подключение специальных библиотек, в случае если ./configure обнаружит всё что ему нужно, он создаст Makefiles — файл, необходимый для сборки программы

Выполнить настройку параметров конфигуратора можно при помощи ключей и аргументов этих самых ключей, например:

./configure —prefix=/opt/my_program

При помощи ключа —prefix= Вы можете указать директорию, которая в дальнейшем будет выступать как префикс для вашей программы (то есть корневая директория). Это связанно с тем что в мире Linux и не только, существует специальная Иерархия Файловой Системы (HFS) в соответствии с которой любая программа, чтобы работать без ошибок, должна быть собрана и установлена.

В файловой системе есть три основных префикса, относительно которых большинство программ конфигурируется, а именно:

  • / — корневая директория операционной системы, так называемый ROOT
  • /usr — директория, в которой находятся приложения пользовательского окружения
  • /usr/local — дополнительная директория для пользовательских программ, собираемых вручную, специально для того чтобы операционная система не превратилась в свалку

Если открыть любую из этих директорий, то можно увидеть очень схожую структуру, как минимум там будут папки: bin, etc, include, libs, sbin.

Если запустить ./configure без ключей, то префиксом по умолчанию (директория, в которую будет установлена собираемая программа) будет /usr/local, помните это если не можете запустить свою программу, возможно у Вас не прописан путь в PATH.

Кроме ключа —prefix в конфигураторе, как правило, имеется ещё множество других ключей, посмотреть их все можно если выполнить:

./configure —help

make

Самая важная и простая команда/программа, выполняет запуск процедуры компиляции приложения из исходного кода. Для своей работы данная программа использует специальные файлы Makefiles, в которых подробно описан процесс сборки приложения со всеми параметрами, которые мы указали конфигуратору. Результатом успешного выполнения команды make будет собранная программа в текущей директории.

make install

Данная команда выполняет непосредственную установку приложения в указанную, на этапе конфигурирования, директорию, после выполнения команды make install вы можете запустить свежеустановленную программу.

Послесловие

Чтобы не писать три команды по очереди можно написать их в одну строку:

Читайте также:  Broadcom bcm43142 driver linux

./configure && make && make install

&& — это оператор И пришедший из языка C/C++, однако, с точки зрения оболочки он означает то, что следующую команду нужно выполнить только в случае успешного выполнения предыдущей команды, это очень удобно если один из этапов завершается с ошибкой.

На самом деле make install так же может выполнить сборку, потому как задача install зависит от задачи all (то есть непосредственно сборки приложения), это означает что этап make можно пропустить и выполнить всего две команды, если записать их в одну строку получится:

./configure && make install

Удачи Вам! И спасибо за то что дочитали!

Источник

What does a typical ./configure do in Linux?

It also provides an interface to configure (aptly) compilation options. ./configure —help will (usually?) give a list of available options.

It runs a script which typically produces makefiles and «configure.h».

The script is written in the lanugage «m4» which is a macro language. The top level macros are found in autoconf.ac or (in older systems) autoconf.in. These expand containing lower level macros which in turn expand into actual tests which create small programs or tasks to check what kind of system you have.

For example AC_CHECK_HEADER([myheader.h], . ) might generate a tiny C program like:

#include "myheader.h" int main(int argc, char** argv)

If the program compiles, the check is considered «passing» otherwise it «fails». The status of such checks often gets reflected in the config.h file. On a passing check, you might find a line in config.h that looks like:

while on a test that fails, it might look like

When configured to work with autoconf in AM_INIT_AUTOMAKE macro, the Makefile can also reference the results of the tests if the variable containing the test result is exported. So if a needed library is located a few different typical locations, or the syntax of «what works» with one of your standard tools (like tar, ar, etc) is different, or the preferred tool is not available, the Makefile will be able to still build the project properly using the different library locations, the different tool syntax, or a different set of tools.

So when dealing with an Autotools project (configure / make / make install) the Makefile really doesn’t contain everything necessary to build the project, it’s generated from the Makefile.in template to specifically match your system when you type «configure».

Источник

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