Как использовать makefile 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.

Иногда возникает ситуация, когда надо что‑то посчитать согласно сложному алгоритму прямо на LapTop/NetTop/DeskTop PC. При этом этот алгоритм написан на Си. Это может быть цифровой фильтр, дискретное преобразование Фурье, генератор QR кода, кусок линейной алгебры с векторами, какое‑то тригонометрическое вычисление, программный модулятор, статистическая обработка случайной величины. Да всё, что угодно! То есть Вы хотите использовать язык Си как гибкий и быстрый калькулятор в Windows. Тут надо написать программу на Си.

Компьютер — это универсальный вычислитель

Или, например, Вы программируете микроконтроллеры на Си и хотите сделать симулятор прошивки в виде консольного приложения. Надо вам, например, прогнать модульные тесты платформа‑независимого кода на «большом компьютере». Потом Вам 80% вероятность, что понадобится конфигуратор прошивки по UART. Потом Вам понадобится консольное приложение Loader для загрузки по UART самой прошивки через BootLoader.

Потом понадобится крохотная PC‑утилита синхронизации для часов реального времени с PC.

Почему именно Си?

  1. Эту LapTop утилиту стоит писать на том же языке, что и прошивку хотя бы по той причине, что можно пере использовать кодовую базу из микроконтроллеров для программирования на DeskTop(е).

  2. Дело в том что язык программирования Си — это самый простой язык программирования из тех, что всё еще более или менее используется в промышленной разработке. По факту в Си только функции и переменные. Тут нет никаких виртуальных функций, шаблонов, делегатов и прочих концепций. В Си всё предельно просто и конкретно.


Разработка под PC это не сross компиляция, как в случае со сборкой артефактов для микроконтроллера, и тут в PC всё в какой‑то степени проще. При сборке Си приложения не надо думать о файле конфигурации компоновщика, как мы это привыкли делать для cross компиляции артефактов для микроконтроллеров (файлы *.ld).

Сперва определимся для какого Target(а) надо собрать бинарь. Надо узнать какой у нас на материнской плате установлен микропроцессор. Такую информацию может показать утилита CPUZ.

В данном случае у меня на одном компьютере Intel Celeron J4125 2Ghz, 4x cores, L1 32kByte, L2 4MByte, 10W. На другом компьютере установлен 64 разрядный микропроцессор AMD Ryzen 5 PRO 3400GE 3.30 GHz.

Но это даже не так важно. Важно какой у нас Instruction Set. В данном случае — x86–64. Это значит, что у нас 64-битный процессор. Получается, что у нас есть выбор: либо ставить 64-битный компилятор Си, либо накатывать 32-битный компилятор Си.

Когда мы пишем программу в Windows мы пишем программу не для микропроцессора. Мы пишем программу для операционной системы. Это главное отличие от программирования для микроконтроллера. Там мы писали монолитную программу для конкретного микропроцессорного ядра (ARM-Cortex M33 или PowerPC). Тут же как правило, нам приходится работать на разных процессорах, однако мы в OS Windows этого даже не замечаем.

Units:

text

bit

N

N

kByte

kByte

MByte

Процессор

bitness

cores

Threads

L1

L2

L3

1

AMD Ryzen 5 PRO 3400GE

64

4

8

32

512

4

2

Intel Celeron J4125

?

4

4

32

?

?

3

Intel Core i7 8550U

64

4

8

32

256

8

Одновременно с этим наш имитатор прошивки должен собираться и запускаться на всех окружениях настольных компьютеров: на работе, дома, в гараже.

Как и в любом деле сначала надо определится с терминологией.

Терминология

Компилятор — программа, переводящая написанный на языке программирования читаемый понятный человеком текст, в набор машинных кодов (человеко‑нечитаемый бинарный код). Программисты это люди, которые как никто приближены к абстракциям. Любой язык программирования, в частности Си — это уровень на коротком можно не думать о наборе команд данного микропроцессора. У процессора нет никаких переменных и функций. Переменные существуют только в сознании программиста. Поэтому нам нужен компилятор Си. Компилятор для каждого Cи файлика производит *.o файлик с родным для данного процессора машинным кодом.

Компоновщик (Linker)— утилита, которая склеивает бинарные файлы *.o в один монолитный исполняемый бинарный файл программы. В нашем случае это *.exe.

Артефакт — результат работы ToolChain(а). В нашем случае это *.exe файл с бинарным файлом программы.

Что надо из софтвера?

Текстовый редактор (Text Editor)

Прежде всего нужен какой‑то текстовый редактор, чтобы написать этот самый исходный текст программы на Си. Тут вариантов масса. NotePad++, Eclipse, MS VS Code.

Сборщик (Build Tools)

В компьютерах ничего само собой не происходит. Компьютеры — это самые ленивые и безынициативные сущности. Им всё надо объяснять максимально подробно и понятно. Поэтому надо явно указать из каких *.с файлов мы хотим собирать программу. Эти файлы надо как-то перечислить проиндексировать. Для этого была создана специальная утилита называемая make. Идея проста. Создается текстовый файл (Makefile) и в нем прописывается правильная последовательность вызова консольных утилит, которая приведет к тому, что на жестком диске появится исполняемый файл с программой.

Препроцессор (Preprocessor)

Это такая консольная утилита (cpp.exe), которая вставляет и заменяет куски текста. Нужна чисто ради удобства написание текста. Препроцессор позволяет полностью исключить такое нехорошее явление как дублирование программного кода. При этом препроцессору абсолютно всё равно с каким языком программирования работать (Cи, C++, DeviceTree, Graphviz, скрипты компоновки и т. п.). Для препроцессора любой язык программирования — это просто текст.

Теперь рассмотрим практические аспекты.

Какой выбрать компилятор Си кода?

Тут есть несколько бесплатных вариантов на выбор.

Компилятор

разрядность генерируемого кода

1

СygWin

64

2

MinGW

32

3

Mingw-w64

64

4

clang

64

5

Tiny C Compiler

32/64

Для программистов микроконтроллеров я настоятельно рекомендую выбрать именно MinGW. Дело в том, что MinGW генерирует 32-битный код. Это как раз соответствует тому, что большинство микроконтроллеров (например ARM Cortex Mx) как раз 32-битные. И Вы так достигните большей совместимости между кодом прошивки микроконтроллера и консольным приложением в Windows.

Вторая причина по которой надо использовать компилятор C:\MinGW\bin\gcc.exe заключается в том, что в окружении MinGW есть заголовочный файл conio.h, который определяет функцию kbhit(). Это нам понадобится для имитации на PC текстового терминала UART-CLI консоли в stdout/stdin.

>C:\MinGW\bin\gcc.exe  --version
gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Набор утилит MinGW преспокойно скачивается и устанавливается как любая другая программа под OS Windows.

Компоновщик (Linker)

Компоновкой занимается утилита ld, которая вызывает collect2. Именно утилита collect2.exe будет выдавать ошибки, если Вы будите вызывать функции без определения их тела.

Что вообще надо из софтвера?

Вот минимальный джентельменский набор для того чтобы собрать программу на Си.

Назначение утилиты

Название утилиты

1

Текстовый редактор

NotePad++.exe

2

Препроцессор

cpp.exe

3

Компилятор

gcc.exe

4

Консольная утилита для удаления файлов или папок

rm

5

Компоновщик

ld.exe

6

Утилита управления ToolChain(ом). Она решает что и в какой последовательности собирать, чтобы получить артефакты

make.exe

7

Утилита анализа получившегося бинаря. Аналог readelf.exe из мира программирования микроконтроллеров

PE explore.exe

Традиционно программы на Си собирают из make скриптов. Вот минималистический makefile для сборки много файлового Си‑проекта на Windows

MK_PATH:=$(dir $(realpath $(lastword $(MAKEFILE_LIST))))
#@echo $(error MK_PATH=$(MK_PATH))
INCDIR += -I$(MK_PATH)

WORKSPACE_LOC:= $(MK_PATH)../../
$(info  WORKSPACE_LOC= $(WORKSPACE_LOC))
INCDIR += -I$(WORKSPACE_LOC)

BUILDDIR := $(MK_PATH)/Build

SRC_PATH :=  $(dir $(abspath $(dir $$PWD) ))
#@echo $(error SRC_PATH=$(SRC_PATH))

OBJDIR := $(SRC_PATH)obj
# the compiler to use

OPT += -DHAS_GCC
CC = C:\MinGW\bin\gcc.exe

# compiler flags:
#  -g    adds debugging information to the executable file
#  -Wall turns on most, but not all, compiler warnings
CFLAGS += -g

#Generate code for 32-bit ABI
CFLAGS += -m32

CFLAGS += -std=c11 -fshort-enums
#CFLAGS += -Og
CFLAGS  += -O0
#CFLAGS  += -Wall
#CFLAGS  +=-pedantic
#CFLAGS += -ftime-report

#files to link:
LFLAGS += -static
#LFLAGS += -lm

EXECUTABLE=firmware_simulator_x86_m

include $(MK_PATH)config.mk

ifeq ($(CLI),Y)
    include $(MK_PATH)cli_config.mk
endif

ifeq ($(UNIT_TEST),Y)
    include $(MK_PATH)test_config.mk
endif

ifeq ($(UNIT_TEST),Y)
    include $(MK_PATH)diag_config.mk
endif

include $(WORKSPACE_LOC)code_base.mk


#@echo $(error SOURCES_C= $(SOURCES_C))
INCDIR := $(subst /cygdrive/c/,C:/, $(INCDIR))
#@echo $(error INCDIR= $(INCDIR))
OBJ := $(patsubst %.c, %.o, $(SOURCES_C))
OBJ := $(subst /cygdrive/c/,C:/, $(OBJ))
#@echo $(error OBJ= $(OBJ))

.PHONY:all

all:$(OBJ) $(EXECUTABLE)

$(EXECUTABLE): $(OBJ)
	$(CC) $(CFLAGS)  $(OBJ) $(LFLAGS) -o $(EXECUTABLE).exe 

%.o: %.c
	$(CC) $(CFLAGS) $(INCDIR) $(OPT) -c $< -o $@ 

clean:
	rm -r $(EXECUTABLE) $(OBJ) 

Тут файлы config.mk, cli_config.mk, test_config.mk и diag_config.mk это просто файлы с перечислением набора переменных окружения для выборочной сборки конкретных исходников из общей кодовой базы. Вот корневой makefile для подключения разных программных компонентов code_base.mk

ifneq ($(CODE_BASE_MK),Y)
    CODE_BASE_MK=Y
    $(info CodeBase Config)

    #@echo $(error WORKSPACE_LOC=$(WORKSPACE_LOC))
    INCDIR += -I$(WORKSPACE_LOC)

    ifeq ($(THIRD_PARTY),Y)
        include $(WORKSPACE_LOC)/third_party/third_party.mk
    endif

    ifeq ($(APPLICATIONS),Y)
        include $(WORKSPACE_LOC)/applications/applications.mk
    endif

    ifeq ($(CONNECTIVITY),Y)
        include $(WORKSPACE_LOC)/connectivity/connectivity.mk
    endif

    ifeq ($(CONTROL),Y)
        include $(WORKSPACE_LOC)/control/control.mk
    endif
    
    ifeq ($(COMPUTING),Y)
        #@echo $(error COMPUTING=$(COMPUTING))
        include $(WORKSPACE_LOC)/computing/computing.mk
    endif

    ifeq ($(SENSITIVITY),Y)
        #@echo $(error SENSITIVITY=$(SENSITIVITY))
        include $(WORKSPACE_LOC)/sensitivity/sensitivity.mk
    endif

    ifeq ($(STORAGE),Y)
        #@echo $(error STORAGE=$(STORAGE))
        include $(WORKSPACE_LOC)/storage/storage.mk
    endif

    ifeq ($(UNIT_TEST),Y)  
        include $(WORKSPACE_LOC)/unit_tests/unit_test.mk
    endif
endif

Конечный make файл может выглядеть например так. Вот тут и индексируют конечные *.c файлы и определяют ключевые слова для препроцессора (начинаются на HAS_XXXXX).


$(info SCHMITT_TRIGGER_MK_INC=$(SCHMITT_TRIGGER_MK_INC))
ifneq ($(SCHMITT_TRIGGER_MK_INC),Y)
    SCHMITT_TRIGGER_MK_INC=Y

    mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
    $(info Build  $(mkfile_path) )

    SCHMITT_TRIGGER_DIR = $(COMPUTING_DIR)/schmitt_trigger

    INCDIR += -I$(SCHMITT_TRIGGER_DIR)
    SOURCES_C += $(SCHMITT_TRIGGER_DIR)/schmitt_trigger.c

    SCHMITT_TRIGGER=Y
    OPT += -DHAS_SCHMITT_TRIGGER

    ifeq ($(DIAG),Y)
        OPT += -DHAS_SCHMITT_TRIGGER_DIAG
        SOURCES_C += $(SCHMITT_TRIGGER_DIR)/schmitt_trigger_diag.c
    endif

    ifeq ($(CLI),Y)
        ifeq ($(SCHMITT_TRIGGER_COMMANDS),Y)
            OPT += -DHAS_SCHMITT_TRIGGER_COMMANDS
            SOURCES_C += $(SCHMITT_TRIGGER_DIR)/schmitt_trigger_commands.c
        endif
    endif
endif

Если говорить метафорично, то Make — это как механическая коробка передач, только для сборки программ. C Make Вы можете буквально контролировать каждую опцию компилятора. Плюс Make в том, что за 60 лет своего существования это теперь самая разобранная и надежная технология из всего Computer Science.

При первой сборке проекта скорее всего выскочит вот эта ошибка. Это значит, что надо переустановить MinGW.


C:\Users\username\AppData\Local\Temp\ccT9XWou.s:54: Error: invalid instruction suffix for `push'
C:\Users\username\AppData\Local\Temp\ccfvWBon.s:19: Error: invalid instruction suffix for `pop'

Надо чтобы команда gcc.exe -dumpmachine после установки показывала mingw32

>C:\MinGW\bin\gcc.exe -dumpmachine
mingw32

Содержимое того Makefile можно представить в виде вот этой простенькой блок схемы ToolChain(а). Тут можно визуально проследить какой путь проходит *.с файл с момента написания до исполнения в Windows.

Схема ToolChain(а) для сборки Си кода

Схема ToolChain(а) для сборки Си кода

В остальном сборка на PC не отличается от сборки для микроконтроллера. В этом и достоинство сборки из Make. При работе с make cборка под любые процессоры выглядит плюс/минус одинаково. Просто по другому определенные переменные окружения: CC LD и т. п. Все те же *.mk файлы подтянутся что и в кодовой базе для прошивок.

Про то как происходит сборка прошивок из-под скриптов можно почитать в этом тексте:

Настройка ToolChain(а) для Win10+GCC+С+Makefile+ARM Cortex-Mx+GDB

.

Когда собралась вся кодовая база бинарь получился всего 1,9MByte

Отладка имитатора прошивки

Артефактом сборки является файл *.exe. Его можно запустить вызвав его из командной строки cmd.

Тут происходит имитация UART-CLI терминала только вместо UART выступают файлы stdin (аналог UART-RX)/stdout (аналог UART-TX).

Можно заметить, что скорость исполнения приложения просто бешеная. За одну секунду супер-цикл успевает прокрутиться аж 11 240 590 раз! В микроконтроллерах это значение обычно было порядка 7588 раз.

диагностика супер цикла в микроконтроллере ARM Cortex-M33

диагностика супер цикла в микроконтроллере ARM Cortex-M33

Получается, что на PC приложение исполняется быстрее в 1481 раз. На три порядка быстрее!

диагностика супер цикла в консольном приложении Win32

диагностика супер цикла в консольном приложении Win32

Вывод

Сборка кода на Cи для DeskTop это весьма полезный навык при отладке микроконтроллерных прошивок. Можно отладить огромные куски платформа независимого кода: CRC, обработку строчек, триггер Шмитта, бинарные протоколы, и т.п.

Также можно собрать проект разными компиляторами: GCC, Clang. И тем самым найти и устранить больше ошибок в кодовой базе.

Как видите, в сборке Си программ на PC, ровным счетом, нет ничего сложного. Надеюсь этот текст поможет большему количеству программистов-микроконтроллеров отлаживать свои приложения на DeskTop PC и создавать, тем самым, отличные программные продукты.

Links

Дайте мне 15 минут, и я изменю ваш взгляд на GDB

Компилятор GCC. Первая программа на Windows

EclipseIDE.Установка, настройка, программирование на С/Installation, configuration, programming in C

Eclipse и MinGW: как указать IDE путь к makefile и файлам проекта; разделение mingw32-make и ключей

Сборка firmware для CC2652 из Makefile

Почему Важно Собирать Код из Скриптов

Настройка ToolChain(а) для Win10+GCC+С+Makefile+ARM Cortex-Mx+GDB

Tiny C Compiler — Summary https://savannah.nongnu.org/projects/tinycc

Вопросы

  1. Какой путь проходит *.с файл с момента написания до момента исполнения?

  2. Что происходит между нажатием на Enter при запуске консольной утилиты в cmd и запуском функции main()?

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Вы собирали Си программы для x86-64 / x86?

Проголосовали 72 пользователя. Воздержались 9 пользователей.

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Вы делаете имитаторы прошивок на PC?

Проголосовали 65 пользователей. Воздержались 10 пользователей.

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Вы писали консольные приложения на Си?

Проголосовал 71 пользователь. Воздержались 10 пользователей.

DOCKER

If you’ve dabbled in programming, especially if you come from a Unix or Linux background, you’re probably familiar with the convenience of Makefiles. For those new to the concept, a Makefile is a special file that describes how to build and compile a program. It dictates what commands need to be run to generate the executable from the code. But what if you’re working on a Windows system? Fear not, dear reader, as we dive into the ins and outs of running a Makefile in a Windows environment.

Understanding Makefiles

Before we jump into running them on Windows, let’s have a quick primer on what Makefiles are. A Makefile is a plaintext file that contains a set of directives used by a make build automation tool to compile and build programs. Essentially, it automates the compilation process, reducing the complexity of firing a series of commands down to just one or a few simple commands.

Commonly, a Makefile includes the following components:

  • Targets: These are the specific tasks or goals defined in the Makefile, such as build, clean or install.

  • Prerequisites: Files that need to be present before a target can be executed, such as source files.

  • Recipes: The commands that make will execute.

For instance, here’s a very simple example of a Makefile:

all: hello

hello: hello.c
    gcc -o hello hello.c

clean:
    rm -f hello

This Makefile has two targets: all (which is often the default goal for a Makefile) and clean. The target hello has a dependency on hello.c file, and the recipe states that gcc (GNU Compiler Collection) should be used to compile the hello.c file into an executable named hello.

Now, let’s get them running on Windows.

Running Makefiles in Windows

1. Using a Compatibility Layer: Cygwin or WSL

Windows lacks the native ability to run Unix-like build scripts out of the box, but that doesn’t mean you’re out of luck. You can use a compatibility layer like Cygwin or the Windows Subsystem for Linux (WSL).

Cygwin is a POSIX compatible environment that runs natively on Windows. After installing it, you can use its terminal just like you would in Unix/Linux to run Makefiles.

WSL, on the other hand, lets you run a Linux distribution alongside your Windows installation. The Windows 10 Spring 2018 update and later versions come with this feature that you can enable and install a Linux distribution of your choice through the Microsoft Store.

Here’s how to use WSL for running Makefiles:

# First, make sure that WSL is enabled and your Linux distro is installed.

# Open your WSL terminal and navigate to your source code directory using `cd`.

cd /mnt/c/path/to/source/code

# Once there, you can use the `make` command as you would in a Linux environment.

make

2. Using MinGW / MSYS

Alternatively, Windows users can install MinGW (Minimalist GNU for Windows), which provides a complete Open Source programming toolset. Along with MinGW, you want to install MSYS, a collection of GNU utilities such as bash, make, gawk, and grep to allow building applications.

Once installed, you can open the MinGW shell and navigate to your project directory where the Makefile resides:

# Run make to compile your code according to the Makefile.
make

3. Installing Make with Chocolatey

For those who wish for a more straightforward method, you can install ‘make’ using a package manager for Windows such as Chocolatey.

First, install Chocolatey following the instructions on their website. Then, run the following command in an administrative command prompt or PowerShell to install make:

Now you can run make from the regular command prompt or PowerShell:

cd path\to\source\code
make

Troubleshooting Common Issues

When running Makefiles in Windows, some common problems can occur:

  • Line Endings: Make sure the Makefile uses Unix-style LF line endings, not Windows-style CRLF.

  • Pathnames: Windows’ pathnames are different from Unix/Linux, so update the Makefile to reflect the correct paths.

  • Command Differences: Some commands in Unix Makefiles may not work in Windows or have different names.

Conclusion

Running Makefiles in Windows isn’t as straightforward as on Unix-like systems, but by leveraging compatibility layers or installing necessary packages through MinGW or Chocolatey, Windows users can enjoy the utility of Makefiles. Following the steps outlined above should provide a smooth experience when dealing with Makefiles, significantly simplifying your C or C++ development process on a Windows system. Happy coding and building!

Remember to test your setup and possibly adapt your Makefiles to accommodate the Windows environment. With a bit of tweaking, the power of Makefiles can be fully harnessed on any platform.

Suggested Articles

DOCKER

DOCKER

DOCKER


Dockerizing Spring Boot Application

Hello, and welcome to our in-depth guide on how to containerize your Spring Boot Application using Docker! If you have been developing applications with Spring Boot, you know how smooth it is to create stand-alone, production-grade applications that …

DOCKER


Fastapi And Redis Cache

Hey folks! After a whirlwind month of back-to-back coding sprints and putting out the proverbial fires, I’m excited to bring you back to our beloved FastAPI series. This time, we’re going to dive into the electrifying world of caching with Redis. Fas…

DOCKER

DOCKER

For software developers working on Windows, the process of running a Makefile can sometimes be a bit tricky. Makefiles are commonly used as build automation tools in software development projects, allowing developers to specify the dependencies and build targets for their code.

Running Makefile on Windows Using Cygwin

However, Makefiles are traditionally used in Unix-based operating systems, and running them on Windows can be challenging.

One popular solution for running Makefile on Windows is using Cygwin, a Unix-like environment and command-line interface for Microsoft Windows. Cygwin provides a collection of tools and libraries that allow you to run Unix applications on Windows, including the GNU Make utility which is used to interpret Makefiles.

What is Cygwin?

Cygwin is a free and open-source software that provides a Unix-like environment on Windows. It consists of a library that emulates the POSIX system calls and a collection of tools that provide a Unix-like command-line interface. With Cygwin, you can run many Unix utilities and applications on Windows, including the GNU Make utility which is essential for running Makefiles.

One of the key features of Cygwin is its ability to provide compatibility between Unix-based systems and Windows. This compatibility allows developers to run Makefile-based build processes on Windows without having to rewrite the build scripts for the Windows environment.

Installing Cygwin

To run Makefile on Windows using Cygwin, you first need to install Cygwin on your Windows system. The installation process is straightforward and involves downloading the Cygwin installer from the official website and running it on your system.

  • Download the Cygwin installer from the official website.
  • Run the installer and select the packages you want to install. Make sure to select the GNU Make package.
  • Follow the on-screen instructions to complete the installation process.

Once you have installed Cygwin on your Windows system, you can open the Cygwin Terminal and navigate to the directory containing your Makefile to run it using the GNU Make utility.

Running Makefile with Cygwin

To run a Makefile on Windows using Cygwin, you first need to open the Cygwin Terminal and navigate to the directory containing your Makefile. Once you’re in the right directory, you can use the make command to run the Makefile and build your project.

For example, if your Makefile is named Makefile, you can run it by typing the following command in the Cygwin Terminal:

make

After running the make command, Cygwin will interpret the Makefile and execute the build process according to the rules specified in the Makefile. You can also pass additional parameters to the make command to specify the build target or any custom options defined in the Makefile.

Benefits of Using Cygwin for Running Makefile on Windows

Using Cygwin to run Makefile on Windows offers several benefits for software developers:

  • Compatibility: Cygwin provides compatibility between Unix-based systems and Windows, allowing developers to run Makefile-based build processes on Windows without any modifications to the build scripts.
  • Productivity: By using Cygwin, developers can leverage the powerful GNU Make utility and other Unix tools to streamline the build process and increase productivity.
  • Flexibility: Cygwin allows developers to run a wide range of Unix utilities and applications on Windows, providing flexibility in development environments and toolsets.

In conclusion, Cygwin is a powerful tool for software developers working on Windows who need to run Makefile-based build processes. By installing Cygwin and leveraging its compatibility with Unix-based systems, developers can streamline their build processes and increase productivity. If you’re looking to run a Makefile on Windows, give Cygwin a try and see how it can improve your development workflow.

Running a Makefile on Windows Using MinGW

In this blog post, we will guide you through the process of running a makefile on Windows using MinGW.

What is MinGW?

MinGW, short for Minimalist GNU for Windows, is a development environment for Windows that allows you to use GNU tools such as GCC and Make to build and run software. It provides a Unix-like environment on Windows, making it easier for developers to work on cross-platform projects.

Setting Up MinGW

The first step in running a makefile on Windows is to install MinGW on your system. You can download the MinGW installer from the official website and follow the installation instructions to set it up on your Windows machine.

Once MinGW is installed, you will need to add the MinGW bin directory to your system Path. This allows you to run MinGW commands from any directory in the command prompt. To do this, go to Control Panel > System and Security > System > Advanced system settings > Environment Variables, and edit the Path variable to include the MinGW bin directory.

Creating a Makefile

Now that you have MinGW set up on your system, you can create a makefile for your project. A makefile is a text file that contains instructions for building your software project, such as compiling source code files and linking them together.

Here is an example of a simple makefile:

  • CC=gcc
  • CFLAGS=-Wall
  • all: hello.exe
  • hello.exe: hello.c
  • $(CC) $(CFLAGS) -o hello.exe hello.c

  • clean:
  • rm -f hello.exe

In this makefile, the CC variable is set to the GCC compiler, and the CFLAGS variable is set to enable all compiler warnings. The all target builds the hello.exe executable from the hello.c source file, and the clean target removes the executable file.

Running the Makefile

To run the makefile on Windows using MinGW, open a command prompt and navigate to the directory where your makefile is located. Run the following command to build the project:

  • make

This command instructs the Make tool to read the makefile and build the project according to the instructions provided. If there are no errors in the build process, you will see the compiled executable file in the same directory.

Benefits of Using MinGW

Using MinGW to run makefiles on Windows offers several benefits to developers:

  • Compatibility: MinGW provides a Unix-like environment on Windows, allowing developers to use familiar tools and workflows.
  • Flexibility: MinGW supports a wide range of GNU tools, making it easy to build and run software projects on Windows.
  • Performance: MinGW delivers high performance and optimization for compiled code, ensuring that your applications run smoothly on Windows.
  • Community Support: MinGW has a large and active community of developers who can provide help and support for using MinGW on Windows.

Running a makefile on Windows using MinGW can help streamline your software development process and improve your productivity as a developer. By following the steps outlined in this blog post and leveraging the power of MinGW, you can easily build and run software projects on Windows with ease.

Have you tried running makefiles on Windows using MinGW? Share your experience with us in the comments below!

Running a Makefile on Windows Using WSL

This is the part where we explore how you can utilize WSL to run a Makefile on Windows.

What is WSL?

WSL is a compatibility layer for running Linux binary executables natively on Windows. It allows developers to use Linux tools and utilities on a Windows machine, providing a seamless experience for cross-platform development. With WSL, you can access the Linux shell and run commands as if you were working on a Linux system.

Setting Up WSL

To run a Makefile on Windows using WSL, you first need to install WSL on your Windows machine. You can enable WSL by following these steps:

  • Open Control Panel and navigate to Programs and Features
  • Click on «Turn Windows features on or off»
  • Check the box next to «Windows Subsystem for Linux» and click OK
  • Restart your computer to apply the changes

Installing a Linux Distribution

Once you have enabled WSL, you can install a Linux distribution of your choice from the Microsoft Store. Popular options include Ubuntu, Debian, and Kali Linux. After installing a Linux distribution, you can launch it from the Start menu and set up your username and password.

Running Makefile on Windows

With WSL set up, you can now navigate to the directory containing your Makefile using the Linux shell. You can use the `cd` command to change directories and the `ls` command to list the contents of a directory.

Once you are in the directory with your Makefile, you can run the `make` command to execute the Makefile. The Makefile will then compile your code according to the rules specified in the Makefile. If there are any errors during the build process, the Makefile will display them in the terminal.

Benefits of Using WSL for Makefiles

Using WSL to run Makefiles on Windows offers several advantages for developers:

  • Cross-platform Development: WSL allows you to leverage Linux tools and utilities on a Windows machine, enabling seamless cross-platform development.
  • Easy Integration: With WSL, you can easily integrate Linux build processes into your Windows workflow without the need for a separate Linux machine.
  • Compatibility: WSL ensures compatibility with Linux-based build systems, making it easier to work on projects that require Linux-specific tools.

Running a Makefile on Windows using WSL provides developers with a convenient way to automate the build process of their projects. By leveraging the power of WSL, you can seamlessly run Linux-based tools and utilities on a Windows machine, streamlining your development workflow and enhancing productivity. Try out WSL today and experience the benefits of cross-platform development on Windows!

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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как установить windows 10 вместо linux mint
  • Paint 3d не запускается в windows 10
  • Visual studio 2012 visual studio express 2012 для windows
  • Как снять режим в самолете на компьютере windows 10
  • Как настроить rdp windows 10 через роутер