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
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
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
.
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.
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
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:
-
Установка 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. Подтвердите выполнение команды, если будет запрошено разрешение.
-
Установка make с помощью Chocolatey:
После установки Chocolatey выполните следующую команду в PowerShell:
choco install make
Chocolatey автоматически загрузит и установит утилиту make
и все необходимые зависимости.
-
Проверка установки:
make --version
Если установка прошла успешно, вы увидите вывод с информацией о версии make
.
Далее, для использования make можно использовать обычный CMD, но, всегда в режиме администратора.
Если было полезно — подписывайтесь и ставьте лайки. Благодарю за внимание.
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .
Создаем SPA на C# и Blazor
stackOverflow 04.05.2025
Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .
Реализация шаблонов проектирования GoF на C++
NullReferenced 04.05.2025
«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .
C# и сети: Сокеты, gRPC и SignalR
UnmanagedCoder 04.05.2025
Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .
Создание микросервисов с Domain-Driven Design
ArchitectMsa 04.05.2025
Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .
Многопоточность в C++: Современные техники C++26
bytestream 04.05.2025
C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .
A commonly asked question is, “can I use Linux makefiles to build on Windows?”
Often, the simple (and rather naive) answer is “use NMake”. This post explains the nuanced differences between a Linux and Windows Makefile.
NMake is the native Windows alternative to the Linux make utility and the syntax is very similar too. However, let’s see if it can handle the following simple Linux Makefile. The example code can be accessed via GitHub at https://github.com/cognitivewaves/Simple-Makefile.
# Specify compiler CC=gcc # Specify linker LINK=gcc # Build all target .PHONY : all all : app # Link the object files and dependent libraries into a binary app : main.o $(LINK) -o app main.o -lstdc++ # Compile the source files into object files main.o : main.cpp $(CC) -c main.cpp -o main.o # Clean target .PHONY : clean clean : rm main.o app
Start a command prompt which can execute NMake
. An easy way is to start a command prompt from Visual Studio (Tools->Visual Studio Command Prompt
), so that all the necessary environment variables are set. Change directory to where the Makefile exists and run NMake.
D:\tmp\Simple-Makefile>nmake Microsoft (R) Program Maintenance Utility Version 10.00.30319.01 Copyright (C) Microsoft Corporation. All rights reserved. gcc -c main.cpp -o main.o 'gcc' is not recognized as an internal or external command, operable program or batch file. NMAKE : fatal error U1077: 'gcc' : return code '0x1' Stop.
The error points to the first problem. It’s easy to fix though as shown in the snippet.
- Compilers are different on Linux and Windows.
# Specify compiler CC=cl.exe # Specify linker LINK=link.exe
Run NMake
again after the change.
D:\tmp\Simple-Makefile>nmake Microsoft (R) Program Maintenance Utility Version 10.00.30319.01 Copyright (C) Microsoft Corporation. All rights reserved. cl.exe -c main.cpp -o main.o Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. cl : Command line warning D9035 : option 'o' has been deprecated and will be removed in a future release main.cpp link.exe -o app main.o -lstdc++ Microsoft (R) Incremental Linker Version 10.00.40219.01 Copyright (C) Microsoft Corporation. All rights reserved. LINK : warning LNK4044: unrecognized option '/o'; ignored LINK : warning LNK4044: unrecognized option '/lstdc++'; ignored LINK : fatal error LNK1181: cannot open input file 'app.obj' NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\link.exe"' : return code '0x49d' Stop.
These warnings and errors indicate the next set of problems, which are more perverse. To fix it, adjust the file as shown in the snippet.
- Libraries are never the same
- Linux uses dash (-) to specify compiler options. Fortunately, Visual Studio allows options to be specified by either a forward slash (/) or a dash (–). But the compiler and linker flags are not exactly the same. There are more differences than similarities.
# Link the object files and dependent libraries into a binary app : main.o $(LINK) /OUT:app.exe main.o # Compile the source files into object files main.o : main.cpp $(CC) /c main.cpp /Fomain.o
Run NMake
again.
D:\tmp\Simple-Makefile>nmake Microsoft (R) Program Maintenance Utility Version 10.00.30319.01 Copyright (C) Microsoft Corporation. All rights reserved. link.exe /OUT:app.exe main.o Microsoft (R) Incremental Linker Version 10.00.40219.01 Copyright (C) Microsoft Corporation. All rights reserved. rm main.o app.exe 'rm' is not recognized as an internal or external command, operable program or batch file. NMAKE : fatal error U1077: 'rm' : return code '0x1' Stop.
These indicate further problems.
- It doesn’t recognize the Linux built in target names like
.PHONY
- Linux commands are obviously not valid in Windows
Finally, to make it work, the following changes have to be made. So Linux makefiles need to be ported to NMake format.
In summary, Linux Makefile
s require some manual effort to run on Windows. Some of the options are,
- Port to Windows NMake format.
- Use a Linux like environment with Cygwin or MinGW to run “as is” on Windows (i.e. without NMake).
- Create an equivalent Visual Studio Solution.
- Create an equivalent CMake project. This is a more elegant alternative as the cross-platform build system CMake can generate Makefiles for Linux and Visual Studio solutions for Windows.
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
.