Make clean all linux

Просто о make

Меня всегда привлекал минимализм. Идея о том, что одна вещь должна выполнять одну функцию, но при этом выполнять ее как можно лучше, вылилась в создание UNIX. И хотя UNIX давно уже нельзя назвать простой системой, да и минимализм в ней узреть не так то просто, ее можно считать наглядным примером количество- качественной трансформации множества простых и понятных вещей в одну весьма непростую и не прозрачную. В своем развитии make прошел примерно такой же путь: простота и ясность, с ростом масштабов, превратилась в жуткого монстра (вспомните свои ощущения, когда впервые открыли мэйкфайл).

Мое упорное игнорирование make в течении долгого времени, было обусловлено удобством используемых IDE, и нежеланием разбираться в этом ‘пережитке прошлого’ (по сути — ленью). Однако, все эти надоедливые кнопочки, менюшки ит.п. атрибуты всевозможных студий, заставили меня искать альтернативу тому методу работы, который я практиковал до сих пор. Нет, я не стал гуру make, но полученных мною знаний вполне достаточно для моих небольших проектов. Данная статья предназначена для тех, кто так же как и я еще совсем недавно, желают вырваться из уютного оконного рабства в аскетичный, но свободный мир шелла.

Make- основные сведения

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

1) целями (то, что данное правило делает);
2) реквизитами (то, что необходимо для выполнения правила и получения целей);
3) командами (выполняющими данные преобразования).

В общем виде синтаксис makefile можно представить так:

То есть, правило make это ответы на три вопроса:

Несложно заметить что процессы трансляции и компиляции очень красиво ложатся на эту схему:

Простейший Makefile

Предположим, у нас имеется программа, состоящая всего из одного файла:

Для его компиляции достаточно очень простого мэйкфайла:

Данный Makefile состоит из одного правила, которое в свою очередь состоит из цели — «hello», реквизита — «main.c», и команды — «gcc -o hello main.c». Теперь, для компиляции достаточно дать команду make в рабочем каталоге. По умолчанию make станет выполнять самое первое правило, если цель выполнения не была явно указана при вызове:

Компиляция из множества исходников

Предположим, что у нас имеется программа, состоящая из 2 файлов:
main.c

Makefile, выполняющий компиляцию этой программы может выглядеть так:

Он вполне работоспособен, однако имеет один значительный недостаток: какой — раскроем далее.

Инкрементная компиляция

Представим, что наша программа состоит из десятка- другого исходных файлов. Мы вносим изменения в один из них, и хотим ее пересобрать. Использование подхода описанного в предыдущем примере приведет к тому, что все без исключения исходные файлы будут снова скомпилированы, что негативно скажется на времени перекомпиляции. Решение — разделить компиляцию на два этапа: этап трансляции и этап линковки.

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

Попробуйте собрать этот проект. Для его сборки необходимо явно указать цель, т.е. дать команду make hello.
После- измените любой из исходных файлов и соберите его снова. Обратите внимание на то, что во время второй компиляции, транслироваться будет только измененный файл.

После запуска make попытается сразу получить цель hello, но для ее создания необходимы файлы main.o и hello.o, которых пока еще нет. Поэтому выполнение правила будет отложено и make станет искать правила, описывающие получение недостающих реквизитов. Как только все реквизиты будут получены, make вернется к выполнению отложенной цели. Отсюда следует, что make выполняет правила рекурсивно.

Фиктивные цели

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

Командой make производят компиляцию программы, командой make install — установку. Такой подход весьма удобен, поскольку все необходимое для сборки и развертывания приложения в целевой системе включено в один файл (забудем на время о скрипте configure). Обратите внимание на то, что в первом случае мы не указываем цель, а во втором целью является вовсе не создание файла install, а процесс установки приложения в систему. Проделывать такие фокусы нам позволяют так называемые фиктивные (phony) цели. Вот краткий список стандартных целей:

  • all — является стандартной целью по умолчанию. При вызове make ее можно явно не указывать.
  • clean — очистить каталог от всех файлов полученных в результате компиляции.
  • install — произвести инсталляцию
  • uninstall — и деинсталляцию соответственно.
Читайте также:  Выключение компьютера при запуске windows

Для того чтобы make не искал файлы с такими именами, их следует определить в Makefile, при помощи директивы .PHONY. Далее показан пример Makefile с целями all, clean, install и uninstall:

Теперь мы можем собрать нашу программу, произвести ее инсталлцию/деинсталляцию, а так же очистить рабочий каталог, используя для этого стандартные make цели.

Обратите внимание на то, что в цели all не указаны команды; все что ей нужно — получить реквизит hello. Зная о рекурсивной природе make, не сложно предположить как будет работать этот скрипт. Так же следует обратить особое внимание на то, что если файл hello уже имеется (остался после предыдущей компиляции) и его реквизиты не были изменены, то команда make ничего не станет пересобирать. Это классические грабли make. Так например, изменив заголовочный файл, случайно не включенный в список реквизитов, можно получить долгие часы головной боли. Поэтому, чтобы гарантированно полностью пересобрать проект, нужно предварительно очистить рабочий каталог:

Для выполнения целей install/uninstall вам потребуются использовать sudo.

Переменные

Все те, кто знакомы с правилом DRY (Don’t repeat yourself), наверняка уже заметили неладное, а именно — наш Makefile содержит большое число повторяющихся фрагментов, что может привести к путанице при последующих попытках его расширить или изменить. В императивных языках для этих целей у нас имеются переменные и константы; make тоже располагает подобными средствами. Переменные в make представляют собой именованные строки и определяются очень просто:

Существует негласное правило, согласно которому следует именовать переменные в верхнем регистре, например:

Так мы определили список исходных файлов. Для использования значения переменной ее следует разименовать при помощи конструкции $( ); например так:

Ниже представлен мэйкфайл, использующий две переменные: TARGET — для определения имени целевой программы и PREFIX — для определения пути установки программы в систему.

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

Автоматические переменные

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

Источник

5 Best Free Linux System Cleaning Tools

There are lots of ways of improving the performance of your computer. We investigated a number of solutions in our feature entitled Ubuntu Tips – Boot Faster which concentrated on shortening the time taken for a machine to boot. These included disabling services that are not needed, concurrent booting, and reprofiling the boot sequence. The article also gave tips on optimizing the general system performance including ways to make more efficient use of memory, improving hard disk performance, and by using a lightweight desktop environment. These can all have a marked effect on minimizing the boot process. However, having a machine that is quick to boot is only one area that needs to be tackled if a computer is going to remain responsive.

Many readers will have witnessed their computer system becoming progressively slower in use over time. This particularly affects Windows so much so that over time it can feel like the machine is running at half speed. This is in part due to users continually installing more applications, and not performing system maintenance. Other factors include ineffective uninstallation routines, Microsoft’s propensity for almost daily patches and security updates, hard drives full of temporary files, a bloated registry, and poorly configured antivirus software. These types of issues also affect Linux albeit to a lesser degree. Nevertheless, if a Linux machine is to remain in pristine condition, there is a genuine need for users to run software that vacuums up the detritus, wiping clean applications, deleting cookies, shredding temporary files, removing logs, and other types of system maintenance.

There are a number of open source applications for Linux which help to keep the operating system working like new. To provide an insight into the software that is available, we have compiled a list of 5 of our favourite open source system cleaning tools. Hopefully, there will be something of interest here for users who want to ensure their computer system retains its vitality.

We have written detailed reviews of Stacer and BleachBit.

You may be surprised to see a package manager included in the list below. We have seen many systems where system performance has been affected simply due to the number of applications that have been installed which are no longer being used on a regular basis. It is worth using a package manager to identify and remove redundant software, thereby freeing up hard disk space, and removing unnecessary daemons, servers, and libraries being loaded in the process.

So, let’s explore the 5 cleaning tools at hand. For each application we have compiled its own portal page, a full description with an in-depth analysis of its features, screenshots, together with links to relevant resources.

Источник

7 Simple Ways to Free Up Space on Ubuntu and Linux Mint

Last updated January 26, 2021 By Abhishek Prakash 168 Comments

Читайте также:  Windows virtual pc диск

Brief: Running out of space on your Linux system? Here are several ways you can clean up your system to free up space on Ubuntu and other Ubuntu based Linux distributions.

Over time, any operating system can become cluttered as programs are added and removed. If you have like a TB of storage capacity, you might not bother to clean up Ubuntu to make some disk space. But if your hard disk has limited space, like I have a 128 GB SSD laptop, freeing up disk space becomes a necessity.

In this article, I’ll show you some of the easiest tricks to clean up your Ubuntu system and get more space. I’ll also share some advanced tricks so that you’ll have choice.

But before that, let’s see how to find the free space remaining on Ubuntu.

Check free space on Ubuntu

It’s always a good idea to check the free disk space in Linux first. This is rather easy on Ubuntu. Just use Disk Usage Analyzer tool. Search it in the menu and run the tool. You should see the disk space used and the free space remaining in here:

Once you know the state of free space on your disk, it’s time to clean up your system and make some more free space here.

How to free up disk space in Ubuntu and Linux Mint

There are several ways you clean up disk space in Ubuntu and other Ubuntu based system. I have discussed several command line tricks here followed by some GUI options.

While I have mentioned several ways here, if you are a beginner, avoid the ones marked as ‘expert’. Not that you cannot use them, but it’s better to avoid if you don’t know what you are doing.

I am using Ubuntu 16.04 while writing this tutorial but you can use the same steps for Ubuntu 18.04 and other Ubuntu versions, Linux Mint, elementary OS and other Ubuntu-based Linux distributions.

If you prefer videos, I have made a video to show you how to clean Ubuntu.

1. Get rid of packages that are no longer required [Recommended]

If you read the apt-get commands guide, you might have come across the apt-get command option ‘autoremove’.

This option removes libs and packages that were installed automatically to satisfy the dependencies of an installed package. If that package is removed, these automatically installed packages are useless in the system.

It also removes old Linux kernels that were installed from automatically in the system upgrade.

It’s a no-brainer command that you can run from time to time to make some free space on your Ubuntu system:

As you can see, this command is going to free up 300 Mb of free space in my system.

We all have a few games and/or applications that we hardly use. Don’t trust me? Go and find all the installed software on your Ubuntu system.

Chances are that you have a number of apps installed that you seldom use. Maybe you installed them on the back of an awesome review, out of nosiness, or to handle a particular task.

If you need space more getting rid of the unused or lesser used applications is always a good idea.

You can remove a program in Ubuntu from the software centre or using the command below with particular app name:

3. Clean up APT cache in Ubuntu

Ubuntu uses APT (Advanced Package Tool) for installing, removing and managing software on the system, and in doing so it keeps a cache of previously downloaded and installed packages even after they’ve been uninstalled.

The APT package management system keeps a cache of DEB packages in /var/cache/apt/archives. Over time, this cache can grow quite large and hold a lot of packages you don’t need.

You can see the size of this cache with the du command below:

As you can see, I have over 500 Mb of cache storage. When you are almost out of space, this 500 Mb can make a lot of difference.

Either remove only the outdated packages, like those superseded by a recent update, making them completely unnecessary.

Or delete apt cache in its entirety (frees more disk space):

4. Clear systemd journal logs [Intermediate knowledge]

Every Linux distribution has a logging mechanism that help you investigate what’s going on your system. You’ll have kernel logging data, system log messages, standard output and errors for various services in Ubuntu.

The problem is that over the time, these logs take a considerable amount of disk space. You can check the log size with this command:

Now, there are ways to clean systemd journal logs. The easiest for you is to clear the logs that are older than a certain days.

Here’s an example:

5. Remove older versions of Snap applications [Intermediate knowledge]

You probably already know that Snap packages are bigger in size. On top of that, Snap stores at least two older versions of the application (in case, you want to go back to the older version). This eats up huge chunk of space. In my case, it was over 5 GB.

Читайте также:  Watching windows во die

Alan Pope, part of Snapcraft team at Canonical, has created a small script that you can use and run to clean all the older versions of your snap apps.

What you have to do here is to create a new shell script and use the following lines in your script:

Give it execute permission, run the shell script with sudo and see the magic. The script removed the older Snap packages and freed over half of the 5 GB space used by Snap.

6. Clean the thumbnail cache [Intermediate knowledge]

Ubuntu automatically creates a thumbnail, for viewing in the file manager. It stores those thumbnails in a hidden directory in your user account at the location

Over time, the number of thumbnails would increase dramatically. Moreover, the thumbnail cache will eventually contain many superfluous thumbnails of pictures that don’t exist anymore.

You can check the size of thumbnail cache with the command below:

For my system, the thumbnail cache is over 300 Mb in size.

So it’s a good practice to clear the thumbnail cache every few months or so. The quickest way is to use the terminal (please copy paste the commands to avoid mistakes):

7. Find and remove duplicate files

Sometimes you may have duplicate files in different places in your system. Getting rid of the duplicates will certainly free up some space and clean your Ubuntu system.

You can use a GUI tool like FSlint or a command line tool like FDUPES for this task. I recommend reading this article to see how to use these tools to remove duplicate files.

4. Remove old Linux kernels that were manually installed [For Experts]

The command discussed in the point 1 removes old Linux kernel. But it won’t work if you manually installed the kernel in Ubuntu. But removing old, unused Linux kernels will still save you plenty of space.

So, if you manually installed a Linux kernel, perhaps you can manually uninstall it as well.

List all installed Linux kernels first:

Removing the old kernels is the same as removing any other package. I’m using shell expansion for the version numbers to save typing. It will prompt you with a list of packages that will be removed, so you can double check the list before continuing.

Note: Replace VERSION with the version of the kernel you want to remove.

My recommendation is to keep at least two or preferably three kernels including the latest. This way, you will have at least one/two other kernels to boot with, if for whatever reason the latest kernel you are unable to boot with.

5. Remove orphaned packages [For Experts]

This step is best avoided if you are a beginner. I am not a fan of this method and I advise you to avoid it.

First, let’s see what is an orphaned package in Ubuntu.

Suppose you installed a package ‘myprogram’. But this package has a dependency on the library ‘mylib’. This lib will be usually installed automatically with ‘myprogram’. When you delete ‘myprogram’, mylib might still remain in the system. Thus mylib, in this case, becomes an orphaned package.

Now, the command listed in point 1 removes such orphaned packages. But imagine the case where you had manually installed mylib before installing myprogram. The command ‘apt autoremove’ might not remove the orphaned package in this case. And hence you’ll have to manually delete it.

You’ll have to find all the orphaned packages first and then remove them. Thankfully, we have a GUI tool to do that: gtkorphan, a graphical frontend for deborphan.

Install gtkorphan via the terminal:

And to remove orphaned packages, search for Removed Orphaned Package tool and run it to find all the orphaned packages in your system:

Honestly, I won’t go for this option unless you really need every Mb of free space.

Bonus Tip: Using GUI tools to free space in Ubuntu

We saw a number of command line options to make space in Linux system but I understand if you don’t want to use the commands.

Remembering all the commands or using them all one by one may not be convenient for you. And this is why we have a number of GUI tools that will help you do that in a few clicks with an easy to use interface.

Stacer is one such tool that you could use. You can read this article to know how to use Stacer in Ubuntu.

You can check out more tools to clean up Ubuntu and make some free space easily.

Wrapping up

So, you saw a number of ways to clean up Ubuntu system. Personally, I use apt-get autoremove more often than any other commands here. Regularly using this command keeps the system free from unnecessary files.

I hope this article helped you to make free space in Ubuntu, Linux Mint and other such distributions. Do let me know if this worked for you or if you have some other tip to share.

Like what you read? Please share it with others.

Источник

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