Как запустить makefile в linux
Перейти к содержимому

Как запустить makefile в linux

  • автор:

Introduction

Makefiles, in simple terms, are files that provide an easy and optimal solution for building and re-building any executable.

It is easy to use, as “make” is the only command that needs to be run, to generate the target executable. It is also optimal, as every time when the same executable is re-built/re-generated, the makefile can selectively generate only those output files whose source files have changed from the previous run.

Makefiles achieve this by maintaining the mapping of all the output files and their respective dependent files and the command which generates that output file. Below is the abstract format of a make file.

Creating a simple makefile

The common way to generate a C executable without using any makefiles is to run the below command.

This would generate the target “main_program” executable file.

Let’s create a makefile for the same program. This is how you create the make file.

Notice that, the target executable is the “main_program” and it has only one dependent file i.e. main_program.c. Also, notice that the corresponding command to generate the main_program executable is mentioned in the second line.

Once the Makefile is set up, all that needs to be done is to run just the “make” command.

When the make command is re-run without modifying the main_program.c file, it can be noticed that the command returns back saying that the executable is already up to date.

Creating a basic make file

Let’s now consider a case where the main_program.c uses a library named libtest.c function. Below is the directory structure and all the relevant files.

The regular way to generate the executable without using any makefiles is mentioned below.

As you can see that, how quickly the number of commands required to generate an executable for a simple program that uses just one library increased significantly. And running this each time when trying to re-build the same executable is not optimal and scalable.

Now, let’s create the make file for this inside the src directory.

You can see that we have set up all the intermediate target output files, their dependent files, and the respective commands that generate the output files. You can also observe that there is a target named clean which deletes all the target object files that shall be generated. The clean gets triggered when “make clean” is run — this can be used as a quick shortcut command to remove all the target files.

Once the make command is triggered, all the target object files are generated with their respective commands.

Let’s now try to modify just the main_program.c file and re-run the make command. This can be done by simply using the touch command on it, which shall change the access time of the file.

You can see that only the main_program object is re-generated as main_program.c is one of its dependent files that has changed. All other object files have not been re-generated as their dependent files had not been altered.

Let’s now try to modify the libtest.o file by using the touch command and then re-run the make command.

As libtest.o is a dependent file for libtest.a, the libtest.a is re-generated. And, as libtest.a has changed, as is a dependent file for main_program executable, main_program is re-generated.

This way makefiles make it easier and optimal to build/re-build executables.

how to run makefile in ubuntu

when I type ./all on my friend’s pc, it shows proper output.

enter image description here

2 Answers 2

Your friend’s PC is doing something strange and its not clear from your question what they’ve done. Your PC is acting normally.

Calling make all Will compile everything, but it doesn’t actually make a program called all . It only compiles two programs: hello.exe and add.exe .

So calling ./all should fail because that is asking to run a program called all which doesn’t exist.

It’s quite possible that your friend has written themselves a program or script called «all». You’ll need to ask your friend what that script / program does and how it does it.

Edit

To see what your friend has done open a terminal on your friends pc (like the one in your screen shot) and type the command

This will list all the files in that directory. Look for one named «all». It might look something like this (with the word «all» in green):

Assuming that’s there you can look at the contents of it by typing

To get yours to work like your friends, create a similar file with the same contents. To make it runnable you may need to change the file permissions:

Что такое Makefile и как начать его использовать

Что такое Makefile и как начать его использовать

В жизни многих разработчиков найдётся история про первый рабочий день с новым проектом. После клонирования основного репозитория проекта наступает этап, когда приходится вводить множество команд с определёнными флагами и в заданной последовательности. Без описания команд, в большинстве случаев, невозможно понять что происходит, например:

Эти команды являются лишь частью того, что необходимо выполнить при разворачивании проекта. В приведённом примере видно, что команды сами по себе длинные, содержат много флагов, а значит, их трудно не только запомнить, но и вводить вручную. Постоянно вести документацию становится сложнее с ростом проекта, она неизбежно устаревает, а порог входа для новичков становится выше, ведь уже никто не в состоянии вспомнить всех деталей проекта. Некоторые такие команды необходимо использовать каждый день, и даже не один раз в день.

Со временем становится понятно, что нужен инструмент, способный объединить в себе подобные команды, предоставить к ним удобные шорткаты ( более короткие и простые команды) и обеспечить самодокументацию проекта. Именно таким инструментом стал Makefile и утилита make . Этот гайд расскажет, как использование этих инструментов позволит свести процесс разворачивания проекта к нескольким коротким и понятным командам:

Что такое make и Makefile

Makefile — это файл, который хранится вместе с кодом в репозитории. Его обычно помещают в корень проекта. Он выступает и как документация, и как исполняемый код. Мейкфайл скрывает за собой детали реализации и раскладывает "по полочкам" команды, а утилита make запускает их из того мейкфайла, который находится в текущей директории.

Изначально make предназначалась для автоматизации сборки исполняемых программ и библиотек из исходного кода. Она поставлялась по умолчанию в большинство *nix дистрибутивов, что и привело к её широкому распространению и повсеместному использованию. Позже оказалось что данный инструмент удобно использовать и при разработке любых других проектов, потому что процесс в большинстве своём сводится к тем же задачам — автоматизация и сборка приложений.

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

Синтаксис Makefile

make запускает цели из Makefile, которые состоят из команд:

Но недостаточно просто начать использовать мейкфайл в проекте. Чтобы получить эффект от его внедрения, понадобится поработать над разделением команд на цели, а целям дать семантически подходящие имена. Поначалу, перенос команд в Makefile может привести к свалке всех команд в одну цель с «размытым» названием:

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

Теперь, когда команды разбиты на цели, можно отдельно установить зависимости командой make install или запустить приложение через make start . Но остальные цели нужны только при первом разворачивании проекта и выполнять их нужно в определённой последовательности. Говоря языком мейкфайла, цель имеет пререквизиты:

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

Теперь развернуть и запустить проект достаточно двумя командами:

Благодаря проделанной работе Makefile, команды проекта вместе с флагами сведены в Makefile. Он обеспечивает правильный порядок выполнения и не важно, какие при этом задействованы языки и технологии.

Продвинутое использование

Фальшивая цель

Использование make в проекте однажды может привести к появлению ошибки make: <имя-цели> is up to date. , хотя всё написано правильно. Зачастую, её появление связано с наличием каталога или файла, совпадающего с именем цели. Например:

Как уже говорилось ранее, изначально make предназначалась для сборок из исходного кода. Поэтому она ищет каталог или файл с указанным именем, и пытается собрать из него проект. Чтобы изменить это поведение, необходимо в конце мейкфайла добавить .PHONY указатель на цель:

Последовательный запуск команд и игнорирование ошибок

Запуск команд можно производить по одной: make setup , make start , make test или указывать цепочкой через пробел: make setup start test . Последний способ работает как зависимость между задачами, но без описания её в мейкфайле. Сложности могут возникнуть, если одна из команд возвращает ошибку, которую нужно игнорировать. В примерах ранее такой командой было создание .env-файла при разворачивании проекта:

Самый простой ( но не единственный) способ «заглушить» ошибку — это сделать логическое ИЛИ прямо в мейкфайле:

Добавлять такие хаки стоит с осторожностью, чтобы не «выстрелить себе в ногу» в более сложных случаях.

Переменные

Зачастую в команды подставляют параметры для конфигурации, указания путей, переменные окружения и make тоже позволяет этим управлять. Переменные можно прописать прямо в команде внутри мейкфайла и передавать их при вызове:

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

Некоторые переменные в Makefile имеют названия отличные от системных. Например, $PWD называется $CURDIR в мейкфайле:

Заключение

В рамках данного гайда было рассказано об основных возможностях Makefile и утилиты make . Более плотное знакомство с данным инструментом откроет множество других его полезных возможностей: условия, циклы, подключение файлов. В компаниях, где имеется множество проектов, написанных разными командами в разное время, мейкфайл станет отличным подспорьем в стандартизации типовых команд: setup start test deploy . .

Возможность описывать в мейкфале последовательно многострочные команды позволяет использовать его как «универсальный клей» между менеджерами языков и другими утилитами. Широкая распространённость этого инструмента и общая простота позволяют внедрить его в свой проект достаточно легко, без необходимости доработок. Но мейкфайл может быть по-настоящему большим и сложным, это можно увидеть на примере реальных проектов:

How to Use make and makefile in Linux

make

One of the main reasons why Linux is popular among C/C++ programmers is the support provided by Linux to them. This includes the g++ compiler suite and its related tools used for program development such as the make command.

In this tutorial, you will learn about the make command in Linux, its use, the basis of the makefile, and how it is used with the make command.

Table of Contents

What is the make command?

Large and complex software applications consist of hundreds of source code and other files. Compiling and linking these files is not easy and can be erroneous. During the build process of these applications, several object files are also created. To manage these files and the entire software development project, the make command is used in Linux.

Consider the case when the programmers have their projects in simple folders. They don’t have any IDE (Integrated Development Environment) such as Eclipse or Visual Studio available to compile and handle their project. The only available option is to use the terminal to compile the source code. Instead of remembering all the commands to compile their files manually, or keeping track of files that are changed and need to be recompiled, they can simply use the make command to handle things for them automatically.

Instead of performing the compilation steps individually and remembering the file names and commands, the make command can be used to automatically perform these tasks. In short, make allows you to automatically build, compile, execute or even install complex software applications using a single command. Thus, it makes the life of a C/C++ programmer easier.

Makefile

The basis of the make command is a text file called Makefile. The Makefile contains the instructions regarding options passed to the compiler.

Makefile is usually created as a text file without any extension, like this

In this file, you can write a set of commands to perform various tasks. For example,

You can consider Makefile as a simple bash script that contains commands to build, compile, and run your code files. Now if you enter the make command like this

it will execute the instructions (commands) written in the Makefile. In the example given above, it will first compile the main.cpp file and will create an executable file named ‘example_code’, then it will execute the ‘example_code’ file.

In this way, you can write multiple commands in the Makefile and execute them all using the simple make command.

Wait, you might be thinking that a Makefile is just like a simple bash script, so what is the big deal? No, the make command can do more than what you just thought, so keep on reading.

Structure of a Makefile

You can set up several targets in a Makefile, which you can then use with the make command. A target can be specified by writing its name followed by a colon ( : ), for example,

here ‘all’ and ‘run’ are targets. By default, the make command will execute the instructions written after the first target (‘all’ in this case).

If you want to execute instructions written after a specific target, you have to specify its name, for example,

This command will run the executable ‘example_code’, as mentioned after the target ‘run’ in the above example.

File dependency

The other important thing you can specify in a Makefile is file dependency. It means that Makefile can specify the code modules which are required to build the program. In addition, it can also specify the required source code files for a particular code module. Therefore, you can use a Makefile for dependency checking.

In a Makefile, you can specify a dependency after the target name is separated by a space, like this

The above line says that the object file ‘main.o’ has a dependency on ‘main.cpp’. In other words, to execute this target the ‘main.cpp’ must exist.

Using make command to delete files

You can use the make command to delete all object and executable files created during the build process. For that, you have to create a target in the Makefile similar to the example given below.

this target when executed (using $ make clean ) will delete all object files and the executable named ‘example_code’.

The use of variables

You can declare and use variables in a Makefile to represent values that might change. For instance, you can represent the name of the compiler using a variable like this

Suppose you want to change the compiler (say to gcc), then you need to change only this value if you are using a variable. There would be no need to change it in all the occurrences in the Makefile because there the name of the variable is used.

You can see a variable is specified with the help of a $ sign. You can also specify options using variables, like

And then use them as shown below:

Remember before using the make command

  • The make command can be used with a simple Makefileor with complex Makefilescontaining several macros or commands. The use of macros with the make command brings application portability. It means the application can be used on other operating systems.
  • If no file is specified, the default Makefilewill be used. If you want to use your Makefilethen you have to specify its name using the -f option.
  • The make command can also be used to install a program. For that you need to specify a target in the Makefile, mentioning the program and pathname in the install command, like the one shown below:

Now, it is also possible to build and install a program in a single step (i.e., by executing the make command). If you want only installation, you can use the following command.

  • If you change any element of a target (such as a source code file), the make command will rebuild the target automatically.

Advantages

Here are some advantages of the make command and the Makefile, which will show you, its importance.

  • It makes the codes easier and clearer to read and removes errors from them.
  • If you make any changes in the program files, you do not need to compile them again and again. Instead, the make command will automatically compile those files only where changes have been done.
  • Makefileis also used to present a project in a more systematic, organized, and efficient way. You can divide a large application program into smaller parts and use the Makefileto handle these smaller parts in different ways.
  • Make command allows us to compile multiple files at once so that all the files can be compiled in a single step which is time-efficient as well.
  • In the case of compiling multiple files, there is no need to type the names of all the files at the command prompt. Remembering their names is difficult and typing their names can be an error-prone task. So, it is easy to write their names once in the Makefileand let the make command handle everything.

Conclusion

In this tutorial, you have studied the make command and Makefile in detail. The make command is used to manage large development projects comprising of tens of source code files. The Makefile is simply a text file that is being used by the make command to set up targets. It allows us to represent the whole project systematically and efficiently thereby making it easier and more readable to debug.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *