I suppose your Makefile is properly formatted, with tabs where they should be, etc.
Then, when you run make install
in the top level directory, your Makefile
does have a rule to make the target install:
it says to loop on your subdirectories, enter each one of them, and run make install
there (this is what the -C
option does). One of those sub-makes fails, most probably because, in its respective subdirectory, it doesn’t find a Makefile
with an install
recipe in it. When the sub-make fails, the loop goes on with the remaining sub-makes (unless the shell was instructed otherwise by means of the -e
switch), and the final return code of the whole recipe will be the return code of the last sub-make.
There are some points worth discussing in your Makefile
(for example, install
should be listed as a .PHONY
target), but you don’t provide enough information to clarify them: for example, is it really necessary to have the shell loop through the subdirectories in a particular order? Usually, a better policy is to have make
parallelize the sub-makes whenever possible (and, as a side effect, have make
stop when the first submake fails…)
This step-by-step troubleshooting guide will help you resolve the make: *** no rule to make target 'install'. stop.
error that occurs during the compilation and installation of a software package from source code. This error typically indicates that the Makefile
doesn’t have a target rule named install
. Follow the steps below to resolve this issue.
Prerequisites
Before proceeding with the troubleshooting steps, ensure that you have the following installed in your system:
- A compatible version of
make
utility - Necessary development tools and libraries for the software package
Table of Contents
- Step 1: Verify the Installation Instructions
- Step 2: Check the Makefile for the Install Target
- Step 3: Look for an Alternative Makefile
- Step 4: Manually Create the Install Target
- FAQs
Step 1: Verify the Installation Instructions
Before diving into the Makefile
, make sure to carefully read the installation instructions provided in the software package. The installation steps may vary depending on the package, so it’s essential to follow the instructions as closely as possible. Look for a README
or INSTALL
file in the package directory and follow the steps mentioned.
Step 2: Check the Makefile for the Install Target
Open the Makefile
in a text editor and search for a target named install
. If you find it, ensure that it’s not commented out. If the install
target is missing, proceed to the next step.
Step 3: Look for an Alternative Makefile
In some cases, the software package may include more than one Makefile
. These alternative Makefile
s may have different names, such as Makefile.install
, Makefile.src
, or Makefile.local
. Check the package directory for any such files and verify if they contain an install
target. If you find a suitable alternative Makefile
, use it with the -f
flag:
make -f Makefile.alternative install
Step 4: Manually Create the Install Target
If none of the above steps work, you can create an install
target manually in the Makefile
. To do this, follow these steps:
- Open the
Makefile
in a text editor. - At the end of the file, add the following lines:
install:
cp binary_name /usr/local/bin/
Replace binary_name
with the appropriate name of the compiled binary generated by the make
command.
- Save the
Makefile
and runmake install
again.
If the above steps don’t resolve the issue, refer to the software package’s documentation, forums, or issue trackers for further assistance.
FAQs
Q1: What does the make: *** no rule to make target 'install'. stop.
error mean?
The error make: *** no rule to make target 'install'. stop.
indicates that the Makefile
doesn’t have a target rule named install
. This target is usually responsible for installing the compiled software binaries and associated files in the appropriate system directories.
Q2: How do I check if the install
target is available in the Makefile
?
Open the Makefile
in a text editor and search for a target named install
. If you find it, ensure that it’s not commented out.
Q3: Can I use an alternative Makefile
with a different name?
Yes, you can use an alternative Makefile
with a different name. To do so, use the -f
flag with the make
command, like this:
make -f Makefile.alternative install
Q4: How do I manually create an install
target in the Makefile
?
To manually create an install
target in the Makefile
, open the file in a text editor and add the following lines at the end:
install:
cp binary_name /usr/local/bin/
Replace binary_name
with the appropriate name of the compiled binary generated by the make
command.
Q5: What should I do if none of the steps in this guide resolve the issue?
If none of the steps in this guide resolve the issue, refer to the software package’s documentation, forums, or issue trackers for further assistance.
- GNU Make Manual
- Introduction to Makefiles
- Common Makefile Mistakes
fairly new to debian and trying to make my first project but I keep running into errors.
Following this tutorial: https://opensource.com/article/19/2/wifi-picture-frame-raspberry-pi
Which leads to this github repo under the «building debian» section: https://github.com/nextcloud/client_theming
I did not follow the install debian section as I already have it installed with raspbian?
I ran the commands below with no error.
cmake -D OEM_THEME_DIR=$(realpath ../nextcloudtheme) -DCMAKE_INSTALL_PREFIX=/usr ../client
make
When I run the next command in the sequence «sudo make install», I receive the following error:
make: *** No rule to make target 'install'. Stop.
Within the client folder, which is where the build was created, there are these files:
CMakeCache.txt CMakeFiles cmake_install.cmake CMakeLists.txt Makefile
I have tried cd CMakeFiles and running «sudo make install» within that folder but receive the same error. From my research online, there should be a file within the client folder with the word «install» attached to it and the make command should loop through and find it. I have the install file, however this may not be the correct one? Suggestions are appreciated, thank you!
Hello @missinglink , I am using this for a long time. Recently I am upgrading all my stuff to Ubuntu 22.04. I am also using libpostal within a docker so an automated script is needed. When I got all the errors then I started R&D using a fresh Ubuntu Image. I got few answers here also
R&D 1: using make j4
OS: Ubuntu 22.04
Script:
mkdir -p /opt/locusq/geocoding/libpostal_data
git clone https://github.com/openvenues/libpostal.git
cd libpostal
make distclean
./configure --datadir=/opt/locusq/geocoding/libpostal_data
make -j4
make install
Result:
make distclean
returning
make: *** No rule to make target ‘install’. Stop.
make j4
returning
If I use make j4
again it is still returning the same error.
R&D 2: using make j2
OS: Ubuntu 22.04
Script:
mkdir -p /opt/locusq/geocoding/libpostal_data
git clone https://github.com/openvenues/libpostal.git
cd libpostal
make distclean
./configure --datadir=/opt/locusq/geocoding/libpostal_data
make -j2
make install
Result:
make distclean
returning
make: *** No rule to make target ‘install’. Stop.
make j2
returning
If I run make j2
after the first error then the installation is successful.
R&D 3: using make j1
make j1
also producing the same result as make j2
Please if you have time pay attention to this matter.
I am doing an install of git on Ubuntu 20.04, according to this tutorial. I executed from «Install Git on Linux«, the Debian/Ubuntu parts. And then I get the errors:
make: *** No rule to make target 'all'. Stop.
make: *** No rule to make target 'install'. Stop.
at point 3 under «Build Git from source on Linux«. I am new to Linux, but it seems as though make
is automatically installed. When I run:
apt list --installed
it is listed:
make/focal,now 4.2.1-1.2 amd64 [installed,automatic]
Can you help on how to take this forward or approach learning about the problem?
If I use make j4
again it is still returning the same error.
R&D 2: using make j2
OS: Ubuntu 22.04
Script:
mkdir -p /opt/locusq/geocoding/libpostal_data
git clone https://github.com/openvenues/libpostal.git
cd libpostal
make distclean
./configure --datadir=/opt/locusq/geocoding/libpostal_data
make -j2
make install
Result:
make distclean
returning
make: *** No rule to make target ‘install’. Stop.
make j2
returning
If I run make j2
after the first error then the installation is successful.
R&D 3: using make j1
make j1
also producing the same result as make j2
Please if you have time pay attention to this matter.
I am doing an install of git on Ubuntu 20.04, according to this tutorial. I executed from «Install Git on Linux«, the Debian/Ubuntu parts. And then I get the errors:
make: *** No rule to make target 'all'. Stop.
make: *** No rule to make target 'install'. Stop.
at point 3 under «Build Git from source on Linux«. I am new to Linux, but it seems as though make
is automatically installed. When I run:
apt list --installed
it is listed:
make/focal,now 4.2.1-1.2 amd64 [installed,automatic]
Can you help on how to take this forward or approach learning about the problem?
asked Jul 4, 2021 at 16:23
1
There are multiple ways to install software in Ubuntu. You can install software using APT, Snap, Flatpak, AppImage, installing from source, etc.
As far as what I can understand, you are trying to install git
from source.
I would personally not suggest new Ubuntu/Linux users to install software from source as it is a bit complex than compared to other methods.
In the article which you have mentioned, following these steps will install git
using APT:
Debian / Ubuntu (apt-get)
Git packages are available via apt:
- From your shell, install Git using apt-get:
$ sudo apt-get update
$ sudo apt-get install git
- Verify the installation was successful by typing
git --version
:$ git --version
git version 2.9.2
- Configure your Git username and email using the following commands, replacing Emma’s name with your own. These details will be associated with any commits that you create:
$ git config --global user.name "Emma Paris"
$ git config --global user.email "eparis@atlassian.com"
To know more about installing software in Ubuntu, read these:
- https://medium.com/geekculture/5-different-ways-to-install-software-on-ubuntu-linux-14ae6b95d1d2
- How do I install a .tar.gz (or .tar.bz2) file? (I suggest you research a bit about
checkinstall
.)
answered Jul 4, 2021 at 17:36
Random PersonRandom Person
1,4741 gold badge13 silver badges31 bronze badges
Время на прочтение
6 мин
Количество просмотров 13K
Методы отладки
В этой части поговорим об общих методах и проблемах отладки. В конечном итоге, отладка — это солянка из всего, что работает в данной конкретной ситуации. Эти методы работают для меня и мне приходится полагаться на них даже в случае проблем с простейшими makefile. Может быть, они помогут и тебе тоже.
Отладка Makefile /часть 1/
Один из очень раздражающих багов в make
3.80 был в сообщении об ошибке в makefile, где make
указывал номер строки, и обычно этот номер строки был неверный. Я не удосужился исследовать из-за чего эта проблема возникает: из-за импортируемых файлов, присваиваний многострочных переменных или из-за пользовательских макросов. Обычно, make
дает номер строки больше чем должен был бы. В сложных makefile бывает что номер не совпадает на 20 строк.
Часто наиболее простой путь увидеть значение переменной это напечатать его в ходе выполнения цели. И хотя распечатать легко можно с помощью warning
, в долгой перспективе поможет сэкономить много времени немного усилий на добавление общей цели debug
для вывода переменных. Вот примерный код цели debug
:
debug:
$(for v,$(V),
$(warning $v = $($v)))
Для того чтобы использовать её, нужно перечислить имена переменных которые надо распечатать в командной строке и собрать debug
цель:
$ make V="USERNAME SHELL" debug
makefile:2: USERNAME = Owner
makefile:2: SHELL = /bin/sh.exe
make: debug is up to date.
Если уж совсем делать всё волшебно, то можно использовать MAKECMDGOALS
переменную, чтобы избежать присвоения переменной V
:
debug:
$(for v,$(V) $(MAKECMDGOALS),
$(if $(filter debug,$v),,$(warning $v = $($v))))
Теперь можно выводить переменные просто перечислив их в командной строке. Однако, я не рекомендую этот способ, так как предупреждения make
о невозможности обновлении переменных (так как они указаны как цели) могут сбить с толку:
$ make debug PATH SHELL
makefile:2: USERNAME = Owner
makefile:2: SHELL = /bin/sh.exe
make: debug is up to date.
make: *** No rule to make target USERNAME. Stop.
В то время как make
выводит команды из сценариев цели до их выполнения, он не выводит команды выполняющиеся в shell
функции. Часто эти команды сложные и неуловимые в том плане, что могут выполняться как незамедлительно, так и в отложенной манере, если они были вызваны в значении рекурсивной переменной. Один из способов увидеть эти команды — включить отладку в самой оболочке:
DATE := $(shell date +%F)
OUTPUT_DIR = out-$(DATE)
make-directories := $(shell [ -d $(OUTPUT_DIR) ] || mkdir -p $(OUTPUT_DIR))
all: ;
Если это запустить с опцией отладки sh
, мы увидим:
$ make SHELL="sh -x"
+ date +%F
+ '[' -d out-2004-05-11 ']'
+ mkdir -p out-2004-05-11
Можно заметить, что также выводятся значения всех переменных и выражений.
Часто встречаются сильно вложенные выражения, например, для оперирования с именами файлов:
FIND_TOOL = $(firstword $(wildcard $(addsuffix /$(1).exe,$(TOOLPATH))))
Ничего хорошего в отладке таких выражений нет. Один из разумных подходов будет их разворот и печать каждого подвыражения:
$(warning $(TOOLPATH))
$(warning $(addsuffix /$(1).exe,$(TOOLPATH)))
$(warning $(wildcard $(addsuffix /$(1).exe,$(TOOLPATH))))
Весьма нудно, но без настоящего отладчика это лучший путь (иногда единственный) для определения значений различных подвыражений.
Общие сообщения об ошибках
В руководстве make
есть замечательный раздел со списком сообщений об ошибках make
и их причин. Мы рассмотрим немного из наиболее часто встречаемых. Некоторые описанные проблемы, строго говоря, не являются ошибками make
, такие как синтаксические в командных сценариях, но все же обычными проблемами для разработчиков. Полный список смотри в руководстве.
Сообщение make
об ошибке имеет стандартный формат:
makefile:n: *** message. Stop
или:
make:n: *** message. Stop.
где makefile строка — это имя файла или импортированного файла в котором произошла ошибка. Следующая часть — номер строки, в которой произошла ошибка, далее следуют три звездочки, и, наконец, само сообщение.
Заметим, что это задача make
запускать другие программы и таким образом, если при этом возникают ошибки, скорее всего проблемы в твоём makefile вызвали ошибки в этих других программах. Для примера, ошибки оболочки могут быть из-за плохо сформированных командных сценариев, или ошибок компилятора из-за некорректных аргументов командной строки. Выяснение того, какая программа выдала сообщение об ошибке — первоочередная задача при решении проблемы. К счастью, сообщения make
довольно очевидны.
Синтаксические ошибки
Обычно это типографические ошибки: пропущенные скобки, пробелы после запятых в параметрах функции, и так далее.
Одна из наиболее частых ошибок для новых пользователей make
это опускание скобок вокруг имен переменных:
foo:
for f in $SOURCES;
do
…
done
Скорее всего, make
развернёт переменную $S
в ничего, и оболочка выполнит цикл только раз со значением OURCES
в f
. В зависимости от того, что ты собрался делать с f
, можно получить забавные сообщения оболочки:
OURCES: No such file or directory
но можно и не получить сообщения вовсе. Помни — имена переменных обрамляются скобками.
missing separator
Сообщение:
makefile:2:missing separator. Stop.
или (в GNU make — пер.):
makefile:2:missing separator (did you mean TAB instead of 8 spaces?). Stop.
обычно означает make
искал разделитель, такой как :, =, или табуляцию и не нашел ни одного. Вместо этого, он нашел что-то что он не понял.
commands commence before first target
Эта ошибка появляется в основном в середине makefile, когда строка вне командного сценария начинается с отступа (пробелы или символ табуляции). make
сделает все возможное, чтобы устранить неоднозначность этой ситуации, но если строка не может быть идентифицирована как присваивание значения, условное выражение или многострочное определение макроса, make
решит что это неправильно размещенная команда.
unterminated variable reference
Это простая, но распространённая ошибка. Она означает, что ты забыл закрыть имя переменной или вызов функции правильным количеством скобок. С сильно вложенными вызовами функций и именами переменных make
файлы становятся похожими на Lisp! Избежать этого поможет хороший редактор, который умеет сопоставлять скобки, такой как Emacs.
Ошибки в командных сценариях
Есть три типа частых ошибок в командных сценариях: пропущенная точка с запятой в многострочных командах, незаконченная или неверная переменная пути, или просто команда, которая просто обнаружила проблему в ходе выполнения.
Мы обсуждали пропущенные точки с запятыми в разделе «лучшие практики», поэтому не будем на этом останавливаться здесь.
Классическое сообщение:
bash: foo: command not found
выводится, когда оболочка не смогла найти команду foo
. Так, оболочка поискала в каждой папке из переменной PATH
исполняемый файл и не нашла совпадений. Чтобы исправить такую ошибку, нужно обновить PATH
переменную, обычно в .profile (Bourne shell), .bashrc (bash) или .cshrc (C shell). Конечно, можно также установить PATH
в самом makefile, и экспортировать PATH
из make
.
Если же команда завершилась с ошибкой, она выходит с ненулевым статусом выхода. В этом случае, make
отчитается об ошибке со следующим сообщением:
$ make
touch /foo/bar
touch: creating /foo/bar: No such file or directory
make: *** [all] Error 1
Здесь touch
команда не сработала, что напечатало своё собственное сообщение объясняющее сбой. Следующая строка — это итоговая ошибка make
. Упавшая цель в makefile указана в квадратных скобках, а затем статус выхода упавшей программы. Если программа вышла по сигналу, а не с ненулевым статусом выхода, то make
напечатает более подробное сообщение.
Заметим также, что команды под знаком @
также могут упасть. В этом случае сообщение об ошибке может возникнуть как будто оно из ниоткуда.
В обоих случаях ошибка происходит из программ запускаемых make
, нежели от самого make
.
No Rule to Make Target
Это сообщение имеет две формы:
make: *** No rule to make target XXX. Stop.
и:
make: *** No rule to make target XXX, needed by YYY. Stop.
Это означает, что make
решил обновить файл XXX, но make
не смог найти ни одного правила для выполнения работы. make
ищет во всех явных и неявных правилах в его базе данных прежде чем сдаться и вывести это сообщение.
Есть три причины для этой ошибки:
- В твоем makefile отсутствует необходимое правило для обновления файла. В этом случае тебе необходимо добавить правило с описанием как построить цель.
- В makefile — опечатка. Или
make
ищет неверный файл или в правиле построения этого файла указан неверный файл. Если в makefile используются переменные, то опечатки становится еще труднее отыскать. Иногда единственный путь быть точно уверенным в значении сложного имени файла это напечатать его или печатая переменную напрямую или исследуя внутреннюю базу данныхmake
. -
Файл должен быть, но
make
не находит его или из-за того, что его нет, илиmake
не знает где его искать. Конечно, иногдаmake
абсолютно прав. Файла нет — похоже мы забыли его скачать из VCS. Еще чаще,make
не может найти файл из-за того, что исходник расположен где-то еще. Иногда исходник в другом дереве исходников, или может файл генерируется другой программой и создался в папке артефактов сборки.Overriding Commands for Target
make
позволяет только один командный сценарий для цели (за исключением «::» правил, которые редко используются). Если встретится больше чем один командный сценарий для одной цели,make
выведет предупреждение:makefile:5: warning: overriding commands for target foo
Также он может вывести сообщение:
makefile:2: warning: ignoring old commands for target foo
Первое предупреждение показывает строку, на которой был найден второй сценарий команд; тогда как второе предупреждение указывает на позицию исходного переопределённого командного сценария.
В сложных makefile цели часто определены несколько раз, каждый раз добавляя еще собственные требования. Одно из этих определений цели обычно содержит командный сценарий, но в ходе разработки или отладки очень легко добавить еще один и не заметить, что существующий набор команд уже переопределен.
Например, мы могли бы определить общную цель во включаемом файле:
# Create a jar file.
$(jar_file):
$(JAR) $(JARFLAGS) -f $@ $^
и позволим нескольким отдельным makefile добавить свои собственные требования. Мы могли бы записать в makefile:
# Set the target for creating the jar and add prerequisites
jar_file = parser.jar
$(jar_file): $(class_files)
Если непреднамеренно добавить командный сценарий в такой makefile, make
выдаст предупреждение переопределения.
No rule to make target | |
GNUmakefile:1: *** missing separator. Stop. | |
Syntax error : end of file unexpected (expecting «fi») | |
OLDPWD not set | |
@echo: command not found | |
-bash: make: command not found | |
Похожие статьи |
No rule to make target
make: *** No rule to make target ‘main.cpp’, needed by ‘main.o’. Stop.
GNUmakefile:1: *** missing separator. Stop.
Если вы видите ошибку
GNUmakefile:1: *** missing separator. Stop.
Обратите внимание на GNUmakefile:1:
1 — это номер строки, в которой произошла ошибка
Возможно где-то вместо табуляции затесался пробел. Напоминаю, что в makefile отступы должны быть заданы табуляциями.
Либо таргет перечислен без двоеточия .PHONY clean вместо .PHONY: clean
Либо какая-то похожая ошибка.
Syntax error : end of file unexpected (expecting «fi»)
Если вы видите ошибку
Syntax error : end of file unexpected (expecting «fi»)
Обратите внимание на расстановку ; в конце выражений и расстановку при переносе строк.
Изучите этот
пример
и сравните со своим кодом.
OLDPWD not set
Если внутри makefile вы выполняете cd и видите ошибку
OLDPWD not set
Попробуйте сперва явно перейти в текущую директорию с помощью
CURDIR
cd $(CURDIR)
@echo: command not found
Если внутри makefile вы пытаетесь подавить вывод echo и получаете
@echo: command not found
Скорее всего echo это не первая команда в строке
НЕПРАВИЛЬНО:
if [ ! -f /home/andrei/Downloads/iso/centos_netinstall.iso ]; then
rm ./CentOS-7-x86_64-NetInstall-*;
wget -r -np «http://builder.hel.fi.ssh.com/privx-builds/latest/PrivX-master/Deliverables/» -A «CentOS-7-x86_64-NetInstall-2009.iso
-*.iso;
else
@echo «WARNING: centos_netinstall.iso already exists»;
ПРАВИЛЬНО:
@if [ ! -f /home/andrei/Downloads/iso/centos_netinstall.iso ]; then
rm ./CentOS-7-x86_64-NetInstall-*;
wget -r -np «http://builder.hel.fi.ssh.com/privx-builds/latest/PrivX-master/Deliverables/» -A «CentOS-7-x86_64-NetInstall-2009.iso
-*.iso;
else
echo «WARNING: centos_netinstall.iso already exists»;
-bash: make: command not found
Ошибка
-bash: make: command not found
Означает, что make не установлен.
Установить make в rpm системах можно с помощью yum в deb система — с помощью apt
sudo yum -y install make
sudo apt -y install make
make | |
Основы make | |
PHONY | |
CURDIR | |
shell | |
wget + make | |
Переменные в Make файлах | |
ifeq: Условные операторы | |
filter | |
-c: Компиляция | |
Linux | |
Bash | |
C | |
C++ | |
C++ Header файлы | |
Configure make install | |
DevOps | |
Docker | |
OpenBSD | |
Errors make |