Аналог 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.

Реализация DI в PHP

Jason-Webb 13.05.2025

Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .

Обработка изображений в реальном времени на C# с OpenCV

stackOverflow 13.05.2025

Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .

POCO, ACE, Loki и другие продвинутые C++ библиотеки

NullReferenced 13.05.2025

В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .

Паттерны проектирования GoF на C#

UnmanagedCoder 13.05.2025

Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .

Создаем CLI приложение на Python с Prompt Toolkit

py-thonny 13.05.2025

Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .

Конвейеры ETL с Apache Airflow и Python

AI_Generated 13.05.2025

ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .

Выполнение асинхронных задач в Python с asyncio

py-thonny 12.05.2025

Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .

Работа с gRPC сервисами на C#

UnmanagedCoder 12.05.2025

gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .

CQRS (Command Query Responsibility Segregation) на Java

Javaican 12.05.2025

CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .

Шаблоны и приёмы реализации DDD на C#

stackOverflow 12.05.2025

Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .

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 Makefiles 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.

gnumake-windows

Instructions for building Gnu Make as a native windows application

All patches under the same license as sources of Gnu Make: GPLv3 or later

Author of the patches: Michael M. Builov (mbuilov@yandex.ru)

Fixed Windows-specific bugs:

  • detect too small or empty source Makefile
  • don’t hang on Ctrl-C

Other fixes:

  • fix for inconsistency with fake function arguments, see http://savannah.gnu.org/bugs/?49841
  • ability to enable/disable warnings about use of undefined numeric variables (function arguments)
  • optimizations for Gnu Make functions: expand, sort, filter
  • support for ANSI color escape sequences in Windows console

Instructions for building native gnumake.exe for Windows:

make-4.4.1-build.txt

Pre-built executables:

  • gnumake-4.4.1.exe — gnu make 4.4.1 built for windows7/x86
  • gnumake-4.4.1-x64.exe — gnu make 4.4.1 built for windows7/x64
  • gnumake-4.4.1-ign-case.exe — gnu make 4.4.1 built for windows7/x86
  • gnumake-4.4.1-ign-case-x64.exe — gnu make 4.4.1 built for windows7/x64

ign-case

Variants for makefile writers

  1. added warnings about use of environment variables
  2. extra warnings about use of undefined variables
  3. run with implicitly added -rR —warn-undefined-variables switches
  • gnumake-4.4.1-dev.exe — gnu make 4.4.1 built for windows7/x86 (development version)
  • gnumake-4.4.1-dev-x64.exe — gnu make 4.4.1 built for windows7/x64 (development version)
  • gnumake-4.4.1-ign-case-dev.exe — gnu make 4.4.1 built for windows7/x86 (development version)
  • gnumake-4.4.1-ign-case-dev-x64.exe — gnu make 4.4.1 built for windows7/x64 (development version)

  1. Can I run make command in Windows?
  2. What is make command in CMD?
  3. How do you use make command?
  4. What is the alternative of make command in Windows?
  5. What is make build?
  6. Why make and make install?
  7. What is make and makefile?
  8. What is makefile used for?
  9. How do I run a makefile?
  10. What is make all command?
  11. Does Cygwin have make?

Can I run make command in Windows?

If it is a «NMake Makefile», that is to say the syntax and command is compatible with NMake, it will work natively on Windows. Usually Makefile.

What is make command in CMD?

make is a program that interprets a makefile and executes the commands in the makefile. But, what are those commands? If you look at your makefile you will see UNIX-style commands that are available in Linux, Mac OS X, or Cygwin but are not available in an off-the-shelf Windows system.

How do you use make command?

make is invoked with a list of target file names to build as command-line arguments: make [TARGET …] Without arguments, make builds the first target that appears in its makefile, which is traditionally a target named all. make decides whether a target needs to be regenerated by comparing file modification times.

What is the alternative of make command in 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.

What is make build?

In software development, Make is a build automation tool that automatically builds executable programs and libraries from source code by reading files called Makefiles which specify how to derive the target program.

Why make and make install?

make without parameters takes the ./Makefile (or ./makefile) and builds the first target. By convention, this may be the all target, but not necessarily. make install builds the special target, install. By convention, this takes the results of make all , and installs them on the current computer.

What is make and makefile?

Make is Unix utility that is designed to start execution of a makefile. A makefile is a special file, containing shell commands, that you create and name makefile (or Makefile depending upon the system). … The makefile contains a list of rules. These rules tell the system what commands you want to be executed.

What is makefile used for?

If you want to run or update a task when certain files are updated, the make utility can come in handy. The make utility requires a file, Makefile (or makefile ), which defines set of tasks to be executed. You may have used make to compile a program from source code.

How do I run a makefile?

Also you can just type make if your file name is makefile/Makefile . Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

What is make all command?

‘make all’ simply tells the make tool to build the target ‘all’ in the makefile (usually called ‘ Makefile ‘). You may have a look at such file in order to understand how the source code will be processed.

Does Cygwin have make?

When you get to the screen that lets you select packages to install, find make and select it (it’s probably under «Development» or something similar). Then you’ll be able to run make from the Cygwin bash command line. It is in the package make: The GNU version of the ‘make’ utility .

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как установить edge на windows 10 ltsb
  • Драйвер для atheros ar5b22 windows 10
  • Не открывается диспетчер задач windows 11 после обновления
  • По какому телефону активировать windows
  • Driver nvidia geforce gts 450 windows 7