Как использовать make в windows

This article explores alternatives to Makefiles on Windows. Earthly provides a consistent, containerized build environment for Windows users. Check it out.

As the field of DevOps and build release engineering continues to grow, many new tools are being developed to help make building and releasing applications easier. One of the tools that has been in use for many years is Make, which is still heavily used by engineers today.

A Makefile is a simple text file consisting of targets, which can invoke different actions depending on what has been configured. For example, with a Makefile, you can invoke a build of your application, deploy it, or run automated tests and it can dramatically increase the efficiency of your workflow.

Initially, it was Stuart Feldman who began working on the Make utility back in 1976 at Bell Labs. However, the version of Make most commonly used today is GNU Make, which was introduced in the late 1980s.

While the tool was originally meant to run on Linux, Make’s popularity has interested those working on other operating systems as well. There are several ways to run Makefiles on Windows, and in this article you’ll be introduced to each option and learn about their strengths and weaknesses.

Using Make on Windows

windows

Before looking at the different options available, you should know why you want to run Makefiles on Windows in the first place. Or rather, if you’re working on Windows, why are you even interested in Makefiles?

Historically, the biggest reason for wanting Makefiles to run on Windows is that the developers in your organization are working on Windows. Seeing as how the de facto standard for languages like C and C++ is to use Make, it’s no wonder that Windows users want the ability to use Make as well.

As applications and infrastructure become more modern, the cloud is another reason for wanting Makefiles on Windows. Many infrastructure engineers want their applications to be run on Linux, likely led by the adoption of tools like Docker and containerization in general. Additionally, on Linux, a Makefile is the primary tool to use in many cases, especially when it comes to building native Linux applications. However, many engineers are still using Windows on their workstations, leading to the question of how to run Makefiles on Windows. Let’s dive into the possible answers.

Chocolatey

chocolatey

Linux users have been using package managers for decades, yet they’ve never gained much traction on Windows. Up until the release of winget, the concept of a package manager was never something that was natively included on Windows. Instead, Rob Reynolds started working on an independent package manager back in 2011 that would come to be known as Chocolatey. Chocolatey is now widely used on Windows to install packages, and you can use it to install make as well.

To do so, run the following command in an Administrative PowerShell window:

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

You can find the newest installation instructions at any time on the Chocolatey website.

Once Chocolatey is installed, you may have to close down the PowerShell window and open it back up. After that, run the following command:

Once the script is done running, make will be installed. You may need to restart the PowerShell window again, but at this point you are ready to use Makefiles on Windows.

Chocolatey will likely be the most popular option for those who want to stick to a pure Windows installation. It’s easy to install, easy to use, and you don’t need to jump through any hoops or workarounds to get it working.

At this point, you can use make just like you otherwise would, and you can test it by running make -v.

Cygwin

Historically, one of the most popular ways of running any type of Linux functionality on Windows has been to use Cygwin. Cygwin aims to give a Linux feeling to Windows by holding a large collection of GNU and open source tools. It’s important to note that this does not mean it will give you native Linux functionality. However, it does allow you to use Linux tools on Windows. There’s a big difference between the two; for instance, Cygwin does not have access to Unix functionality like signals, PTYs, and so on. It’s a great tool for when you want to use familiar Linux commands but still want them to be run on Windows.

To use Cygwin for Makefiles, start by downloading and installing Cygwin. During the installation, you’ll see a window popping up asking you what packages you want to install. In the top left corner, make sure to select Full and then search for make.

Searching for “make”

Your search will give you a list of several different packages. You want to choose the one that’s labeled just as make. Change the dropdown menu where it says Skip to the latest version.

Choosing “make”

Now you can finish the installation by clicking Next in the bottom right corner. Once the installation is done, you can open up Cygwin and verify that make has been installed by executing make --version.

NMAKE

One of the alternatives that you’ll often hear about regarding running Makefiles on Windows is NMAKE. While it is an alternative to make, note that you cannot simply take your existing Makefiles from Linux and run them using NMAKE; they have to be ported.

First of all, the compilers are different on Windows and Linux, so if you are specifying your compiler in your Makefile, you’ll have to change that to whatever is relevant on Windows. At the same time, you’ll have to change the flags that you send to the compiler, because Windows typically denotes the flags using / instead of -.

On top of that, it doesn’t recognize all the syntax that you’re used to from GNU Make, like .PHONY. Lastly, Windows obviously doesn’t recognize the commands that work on Linux, so if you have specified any Linux-specific commands in your Makefiles, you’ll also have to port them.

All in all, if your entire organization uses Windows and you simply want the typical functionality of GNU Make, then NMAKE is a viable solution. However, if you just want to quickly run your traditional Makefiles on Windows, NMAKE is not the answer.

CMake

cmake

As with NMAKE, CMake is not a direct way to run your Makefiles on Windows. Instead, CMake is a tool to generate Makefiles, at least on Linux. It works by defining a CMakeLists.txt file in the root directory of your application. Once you execute cmake, it generates the files you need to build your application, no matter what operating system you’re on.

On Linux, this means that it creates Makefiles for you to run, but on Windows it may mean that it creates a Visual Studio solution.

CMake is a great solution if you don’t care too much about running Makefiles specifically, but you want the functionality, namely the ease of use in a build process, that you can get from Makefiles.

Windows Subsystem for Linux

The Windows Subsystem for Linux (WSL) is an honorable mention. It’s cheating a bit to say that it’s a way to run Makefiles “on Windows,” as your Makefiles won’t actually be running on Windows.

If you haven’t heard of WSL before, here’s an extremely oversimplified explanation: It uses Hyper-V to create a hyper-optimized virtual machine on your computer, in which it runs Linux. Basically, you get a native Linux kernel running on your Windows computer, with a terminal that feels as if it’s part of Windows.

You should look into WSL if what you care about most is having Windows as your regular desktop environment, but you’re fine with all of your programming and development going on inside of Linux.

Conclusion

As you can see, there are a few different ways you can be successful in running Makefiles on Windows. However, you do need to be wary of the fact that it will never be a perfect solution. Every solution is in some way a workaround, and the closest you’ll get to feeling like you’re using native Makefiles while using Windows is to install something like WSL.

If you enjoyed this tutorial you might want to grab a copy the free eBook “Makefile ins and outs”. In it you’ll learn many tips and tricks for structuring builds and scaling up a build process. From how to write a simple Makefile to how to deal with dependencies and everything in between. Download this free Makefile book right now.

Как запустить Make на Windows

Make — это широко используемая для автоматизации сборки проектов утилита, которую бывает проблематично установить и запустить на windows. Сегодня я поделюсь самым простым способом, который позволит вам это сделать. Использовать мы будем Chocolatey.

Chocolatey (choco) — это менеджер пакетов для Windows, который позволяет устанавливать и управлять программным обеспечением из командной строки. Вот как установить утилиту make на Windows с помощью Chocolatey:

  1. Установка Chocolatey:

  • Откройте PowerShell от имени администратора.

  • Вставьте следующую команду и нажмите Enter:

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

Эта команда скачает и запустит скрипт установки Chocolatey. Подтвердите выполнение команды, если будет запрошено разрешение.

  1. Установка make с помощью Chocolatey:

После установки Chocolatey выполните следующую команду в PowerShell:

choco install make

Chocolatey автоматически загрузит и установит утилиту make и все необходимые зависимости.

  1. Проверка установки:

make --version

Если установка прошла успешно, вы увидите вывод с информацией о версии make.

Далее, для использования make можно использовать обычный CMD, но, всегда в режиме администратора.

Если было полезно — подписывайтесь и ставьте лайки. Благодарю за внимание.

Make in Windows

Description of how to install and use Make in Windows OS.

There are several ways to install Make on Windows. In this tutorial we will use Git Bash because it is also needed for on Windows, so you might already have that if you followed the steps in . The steps follow the instructions detailed . After installing Git & Git Bash:

  • Download make-4.4-without-guile-w32-bin.zip (get the version without guile).

  • Copy the contents to your C:\Program Files\Git\mingw64\ merging the folders, but do NOT overwrite/replace any existing files.

Using Makefiles in different environments

Commands are called differently in different environments, for example, if you want to run Stata in Git Bash terminal on Windows you should use StataMP-64, but stata on Mac and Linux. Aliases don’t work well in our setting (as Make is run in Git Bash, but Make itself uses the sh shell). Although if you include an operation system detector part at the beginning of your Makefile, it provides a simple solution for a reproducible Makefile in different environments.

Let’s create a project folder called trial/, where the codes can be run with a Makefile both on Windows and Mac or Linux. There should be 2 files in the folder: trial.do and Makefile. The trial.do creates a trial.log just to see and check whether Make runs correctly. The content of trail.do is the following:

capture log close
log using "trial.log", replace text
disp "DateTime: $S_DATE $S_TIME"
log close

You can copy the following content in your Makefile:

#OS detector part
ifeq ($(OS),Windows_NT) # is Windows_NT on XP, 2000, 7, Vista, 10... STATA := StataMP-64 else STATA := stata endif

#Code starts here
trial.log: trial.do $(STATA) -e do $<

When you finished, open the Git Bash terminal, go to the trial/ folder where the trail.do and your Makefile is, and then run make.

$ cd ~/.../trial/
$ ls
  trial.do
  Makefile
$ make

Afterward, you should see the trial.log created by the Makefile.

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Make is an incredibly powerful tool for managing application compilation, testing and installation, or even setting up the development environment. It comes standard on Linux and macOS, and it is therefore widely adopted. But how can you get started with Make on Windows?

I’ve previously written about using Make for Python development, you might find it interesting.

If you are using Windows Subsystem for Linux (WSL/WSL2), then you can easily install make with the sudo apt install make command. However, if you want to have the command available natively on a normal terminal prompt then you need to install a Windows-specific version.

How to install Make on Windows?

The easiest way to configure Make is to use the Chocolatey package manager for Windows. It will handle downloading the correct executable, installing it, and making sure that the command is added to the system path.

  1. Install Chocolatey if you don’t already have it installed
  2. Open an elevated terminal (Run as administrator)
  3. Type the command choco install make, approve the installation if prompted

Next, verify that make works, and then you can start using it normally:

>> make --version
GNU Make 4.3
Built for Windows32
Copyright (C) 1988-2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Alternatively, if you’d prefer to use the new native Windows package manager you can use this winget command:

>> winget install GnuWin32.Make

This will download the installer and run it for you automatically. Make will also be added to the list of installed programs so you can uninstall it from the Add or remove programs section. You will still get the following error since the installer does not add make to the system path:

make : The term 'make' is not recognized as the name of a cmdlet, 
function, script file, or operable program...

To make it executable you need to open the Start menu and search for Edit the system environment variables. Click Environment Variables, then under System variables choose Path and click Edit. Click New and insert C:\Program Files (x86)\GnuWin32\bin, then save the changes. Open a new terminal and test that the command works.

As of writing this article the current version that gets installed with winget is 3.81, so it is older than the one from Chocolatey. You may want to take that into consideration when choosing the installation method. You can check which version would be installed with winget show GnuWin32.Make.

Using Make on Windows

From a syntax perspective there is no difference between Linux and Windows. You still need to write a Makefile and define the shell commands in tab-indented sections. However, the commands themselves need to be adjusted for the changed operating system.

Normally on a Makefile each line runs on a separate shell. If you need to run many commands from the same shell instance then they should be defined on the same line and chained together with the && operator.

.PHONY: test
test: venv
	.\venv\Scripts\activate && python -m unittest discover
	
.PHONY: venv
venv:
	python -m venv venv

The above example defines phony Make targets for setting up a Python virtual environment and running unit tests. Assuming that you have installed Python, running make test should execute successfully, running zero unit tests since it couldn’t find any.

If you need to make your Makefile support different operating systems, then you have to also detect the operating system to be able to run a different set of commands for each OS. With Windows the added difficulty is that in some cases (MSYS, MINGW) you actually need to use the Linux commands.

This answer on Stack Overflow has one solution for finding the correct environment, relying on how the system Path is delimited by semicolons ; unlike all other OSes. We can use that information to make our small example Makefile work natively on both Windows and Linux:

ACTIVATE := ./venv/bin/activate
PYTHON := python3
ifeq '$(findstring ;,$(PATH))' ';'
	ACTIVATE := .\venv\Scripts\activate
	PYTHON := python
endif

.PHONY: venv
venv:
	$(PYTHON) -m venv venv

.PHONY: test
os: venv
	$(ACTIVATE) && $(PYTHON) -m unittest discover

The command for activating the virtual environment is different on Windows compared to other OSes. Also the Python executable is named python on Windows, but on Linux you need to use python3. The conflicting commands can be defined as variables and then referenced in the targets.

Similarly, if you’re compiling C or C++ code, you need to use gcc or g++ on Linux, and cl on the Windows developer command prompt. Also the command arguments will need to be different.

Conclusion

It’s possible to use Make natively on Windows, and it’s not even that difficult. If you’re accustomed to using Bash and Linux commands then the switch to PowerShell commands might require a bit of adaptation. Definitely the biggest challenge is to write Makefiles that support different operating systems, but as we saw that can be accomplished with some tricks.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как в windows 11 отключить группировку иконок панели задач
  • Gpu monitor for windows 7
  • Драйвера для asus x5dij для windows 10
  • Winamp download free for windows 10
  • Windows 10 долго грузится после ввода пароля