Как запустить make в windows 10

I'm following the instructions of someone whose repository I cloned to my machine. I want to use the make command as part of setting up the code environment, but I'm using Windows. I searched onlin...

The chances are that besides GNU make, you’ll also need many of the coreutils. Touch, rm, cp, sed, test, tee, echo and the like. The build system might require bash features, if for nothing else, it’s popular to create temp file names from the process ID ($$$$). That won’t work without bash. You can get everything with the popular POSIX emulators for Windows:

  • Cygwin (http://www.cygwin.org/) Probably the most popular one and the most compatible with POSIX. Has some difficulties with Windows paths and it’s slow.
  • GNUWin (http://gnuwin32.sourceforge.net/) It was good and fast but now abandoned. No bash provided, but it’s possible to use it from other packages.
  • ezwinports (https://sourceforge.net/projects/ezwinports) My current favorite. Fast and works well. There is no bash provided with it, that can be a problem for some build systems. It’s possible to use make from ezwinports and bash from Cygwin or MSYS2 as a workaround.
  • MSYS 1.19 abandoned. Worked well but featured very old make (3.86 or so)
  • MSYS2 (https://www.msys2.org/) Works well, second fastest solution after ezwinports. Good quality, package manager (pacman), all tooling available. I’d recommend this one.
  • MinGW abandoned? There was usually MSYS 1.19 bundled with MinGW packages, that contained an old make.exe. Use mingw32-make.exe from the package, that’s more up to date.

Note that you might not be able to select your environment. If the build system was created for Cygwin, it might not work in other environments without modifications (The make language is the same, but escaping, path conversion are working differently, $(realpath) fails on Windows paths, DOS bat files are started as shell scripts and many similar issues). If it’s from Linux, you might need to use a real Linux or WSL.
If the compiler is running on Linux, there is no point in installing make for Windows, because you’ll have to run both make and the compiler on Linux. In the same way, if the compiler is running on Windows, WSL won’t help, because in that environment you can only execute Linux tools, not Windows executables. It’s a bit tricky!

For tech enthusiasts, Make is a very neat way of building applications. Whether you’re trying to package your app or install somebody else’s, Make makes things easier.

Make isn’t available in Windows. When downloading a Windows application we download a setup file of EXE format. There’s no telling what these setup files may contain. You may even be downloading malware with exe format.

Below we have compiled a few different approaches to installing Make in Windows.

What is Make?

GNU.org tells Make is a tool that controls the generation of programs from its source files. In simple terms, the Make tool takes the source code of the application as input and produces the application as output.

Make is targeted for applications that follow the Free and Open Source Software (FOSS) principle. It was originally designed to work across Linux systems only. The source code can be modified in any way we want before we package it up for use.

Installing Make on Windows

Using Winget

Winget tool by Windows manages installation and upgrade of application packages in Windows 10 and 11. To use this tool, you need to have at least Windows 10 or later installed on your PC.

  1. Press Win + R together to open the Run window.
  2. Type cmd and press Enter to bring up the Command Prompt.
  3. Type the command Winget install GnuWin32.make and press Enter.
    run-cmd-command
  4. Type Y to agree to source agreements.
    type Y to agree cmd-command
  5. After installation, press Win + R again.
  6. Type systempropertiesadvanced and press Enter.
    run menu
  7. Select Environment Variables under the Advanced tab.
    environment-variables
  8. Under System variables, select New.
    new-options
  9. Under the variable name, enter make.
  10. Under Variable value, enter C:Program Files(x86)GnuWin32binmake.exe.
  11. Or, select Browse File and go to the above location.
    variable-value
  12. Press on OK.

Using Chocolatey

Using Chocolatey is a great way to install make if you do not meet the minimum requirements for Winget. It is a package manager and installer for the Windows platform. For anyone familiar with Ubuntu, it is the equivalent of apt command for software installation.

Since Make is not directly available in Windows, we need to install the package manager first. Then, we will use this package manager to install the make tool.

  1. Press Win + X keys together to open the Power menu.
  2. Select Windows Powershell(Admin).
  3. Type the command ‘Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))' and press Enter.
    power-shell-command
  4. Downloads and installs chocolatey as available from their official source.
  5. Type choco to verify if the installation worked.
    powershell-choco
  6. Now, type the command ‘choco install make‘ to install Make.
    install-choco-make
  7. Go to the installation directory C:Program Files(x86)GnuWin32 to confirm the installation worked.

Using WSL

Using WSL or Windows Subsystem for Linux, we can install Make directly on our PC. WSL is released by Windows so this is the most preferred way of installing Make on Windows.

For WSL, we will install Ubuntu inside our Windows.

  1. Press Win + X keys together to open the Power menu.
  2. Select Windows Powershell(Admin).
  3. Type the command ‘Wsl – install‘ and press Enter.
    powershell-wsl--install
  4. Restart your PC.
  5. Go to the Start Menu and type Ubuntu to bring up the Ubuntu command line.
  6. Type the following ‘Sudo apt install gcc build-essential make -y‘ and press Enter.
    powershell-command
  7. Wait until the installation completes.

Using MinGW

MinGW is one of the older ways to install Make on Windows. MinGW is a collection of minimal GNU files for Windows. Note that using this method, you will have to type the ming32-make instead of the make command. Both do the same work except ming32-make is the MinGW version of make.

  1. Download the latest version of MinGW-get-setup.exe.
  2. Install MinGW by opening the setup file.
    install-mingw
  3. Turn off installing graphical interface.
    install--mingw2
  4. Select Continue to start installation.
    mingw-insatallation-package-setup
  5. Go to the installation directory and locate the bin folder.
  6. Make sure MinGW-get.exe exists.
    mingw-exe-file
  7. Press Win + R together to open the Run window.
  8. Type systempropertiesadvanced and press Enter.
  9. Select Environment Variables under the Advanced tab.
    environment-variables
  10. Under System variables, double-click on Path.
    mingw-path
  11. Select New.
    new
  12. Type the location of MinGW-get.exe. E.g. C:MinGWbin
    type-location
  13. Select OK.
  14. Press Win + X together to open the Power menu.
  15. Select Windows Powershell.
  16. Type the command ‘Mingw-get install mingw32-make‘ and press Enter.
    windows-power-shell-command

Using Make on Windows is pretty much the same as Linux or other platforms. You need to start with a makefile along with the source code of the program.

  1. Go to the location of the source code.
  2. Do a right-click and select Text document under New.
  3. Give it the name Makefile.
    makefile
  4. Assuming the source code is source.c, paste the following lines in your makefile as given in this tutorial.
    source code
  5. Finally, open Command Prompt and go to the source code location using the cmd command.
  6. Type make and press Enter.
  7. You can now share and open the output file as an application.
  8. You can also modify the source code source.c any number of times and make will compile it as application output.

If you want to learn more about using the Make command, there’s entire documentation on its usage.

Makefile — это файл утилиты «make», который сохраняется вместе с кодом в репозитории. Makefile помещают в корень проекта, работает он в двух направлениях:

  • как программный код,

  • как документация к проекту.

Сам по себе файл Makefile представляет собой набор структурированных программных команд, которые запускает утилита «make». 

Makefile и утилита «make» представляют собой единый инструмент, который объединяет различные программные команды в одном месте и обеспечивает самодокументирование программы. То есть вы пишите программный код, а он самостоятельно вписывается в файл Makefile в виде уникальной структуры.

Makefile и «make» обязательно нужно использовать в больших проектах, когда программирование ведется в нескольких репозиториях и большим количеством разработчиков. В таких проектах работа ведется в запутанном ритме. Сначала одни программисты работают над репозиторием, потом другие. Потом приходят третьи молодые программисты, пытаются разобраться, что вообще происходит в коде, и не могут, потому что предыдущие профессионалы писали в своем стиле, применяя собственный подход и понимание происходящего. Новичку бывает трудно разобрать запутанный код, потому что никто уже и не помнит, кто и что там писал. Чтобы не было подобных ситуаций, придумали Makefile и утилиту «make». Они все структурируют и облегчают восприятие чужого кода.

Make и Makefile — что это?

Makefile и утилита «make» были придуманы для того, чтобы автоматизировать сборку программ и библиотек из программного кода. Такой функционал оказался востребованным среди программистов, поэтому «эта парочка» быстро обрела популярность. Программисты смекнули, что использовать Makefile можно не только для сборки библиотек, но и в других программах. Главное, за что ценят утилиту «make», — это автоматизация сборки. На сегодняшний день использовать Makefile в большом проекте — это стандарт среди разработчиков любых уровней.

Фактически утилита «make» нужна только для того, чтобы запустить файл Makefile, а точнее, «цели», прописанные в этом файле. Шаблон Makefile выглядит таким образом:

#Makefile

Цель№1: <наименование цели>

   команда№1 #<описывается команда, которая должна выполниться>

   команда№2 #<описывается команда, которая должна выполниться>

Важные замечания по шаблону Makefile:

  • когда задаете имя цели, можно использовать дефис «-» и подчеркивание «_»;

  • список команд будет выполняться в порядке очередности, но каждая следующая команда активируется только в том случае, если предыдущая выполнилась без ошибок;

  • команды разделяются между собой табуляцией — это важно;

  • после того как закончилось описание одной цели, нужно оставить пустую строку, так как пустая строка отделяет одну цель от другой.

Поэтому формирование Makefile в собственном проекте — это ответственное дело. Нужно корректно разделить команды на цели и задать им понятные имена, чтобы потом было легче понять, что за цель была описана. То есть из Makefile не нужно делать «свалку кода» нужно изначально придерживаться строгой и понятной структуры. Таким образом, Makefile будет служить для того, для чего был задуман.

Как запустить Makefile

Если Makefile уже сформирован в программе, тогда запустить его достаточно просто. Главное, чтобы утилита «make» была инсталлирована на вашем устройстве. Обычно она инсталлирована по умолчанию. 

Чтобы запустить «make» в Linux, нужно в терминале ввести команду:

     $ make

После запуска утилита «make» найдет файл Makefile и выполнит первую цель, которая в нем записана. Также при запуске можно указать цель, которую нужно активировать. Например:

     $ make <имя цели>

Если нужно, тогда можно указать несколько целей в одном Makefile, которые нужно активировать.

В Windows также можно запустить файл Makefile. Для этого нужно открыть Visual Studio и перейти в нем в каталог, который содержит файл Makefile. Потом нужно ввести команду:

nmake -f Makefile.win

Заключение

Сегодня мы определили, что такое Makefile. По сути, это файл, который помогает собирать и структурировать большие программы. Он используется совместно с утилитой «make», которая на большинстве устройств предустановлена. Именно при помощи этой утилиты и командной строки можно запустить Makefile. В следующих статьях мы обсудим, как создать и редактировать уже созданный Makefile.

I have some demos that I downloaded and they come with a Makefile.win and a Makefile.sgi. How can I run these in Windows to compile the demos?

0x6B6F77616C74's user avatar

asked Mar 28, 2010 at 7:48

Kim's user avatar

8

You can install GNU make with chocolatey, a well-maintained package manager, which will add make to the global path and runs on all CLIs (powershell, git bash, cmd, etc…) saving you a ton of time in both maintenance and initial setup to get make running.

  1. Install the chocolatey package manager for Windows
    compatible to Windows 7+ / Windows Server 2003+

  2. Run choco install make

I am not affiliated with choco, but I highly recommend it, so far it has never let me down and I do have a talent for breaking software unintentionally.

answered Jul 15, 2019 at 15:05

ledawg's user avatar

ledawgledawg

2,1351 gold badge11 silver badges17 bronze badges

2

If you have Visual Studio, run the Visual Studio Command prompt from the Start menu, change to the directory containing Makefile.win and type this:

nmake -f Makefile.win

You can also use the normal command prompt and run vsvars32.bat (c:Program Files (x86)Microsoft Visual Studio 9.0Common7Tools for VS2008). This will set up the environment to run nmake and find the compiler tools.

answered Mar 28, 2010 at 7:50

Marcelo Cantos's user avatar

Marcelo CantosMarcelo Cantos

179k38 gold badges324 silver badges363 bronze badges

16

Check out GnuWin’s make (for windows), which provides a native port for Windows (without requiring a full runtime environment like Cygwin)

If you have winget, you can install via the CLI like this:

winget install GnuWin32.Make

Also, be sure to add the install path to your system PATH:

C:Program Files (x86)GnuWin32bin

KyleMit's user avatar

KyleMit

36.5k63 gold badges440 silver badges635 bronze badges

answered Jun 6, 2013 at 13:41

Sean Lynch's user avatar

Sean LynchSean Lynch

6,1672 gold badges43 silver badges45 bronze badges

3

Check out cygwin, a Unix alike environment for Windows

answered Mar 28, 2010 at 7:50

Frank's user avatar

FrankFrank

2,32618 silver badges17 bronze badges

4

Here is my quick and temporary way to run a Makefile

  • download make from SourceForge: gnuwin32
  • install it
  • go to the install folder

C:Program Files (x86)GnuWin32bin

  • copy the all files in the bin to the folder that contains Makefile

libiconv2.dll libintl3.dll make.exe

  • open the cmd (you can do it with right click with shift) in the folder that contains Makefile and run

make.exe

done.

Plus, you can add arguments after the command, such as

make.exe skel

Maria Ines Parnisari's user avatar

answered Oct 20, 2017 at 3:59

alan9uo's user avatar

alan9uoalan9uo

97111 silver badges16 bronze badges

4

If you install Cygwin. Make sure to select make in the installer. You can then run the following command provided you have a Makefile.

make -f Makefile

https://cygwin.com/install.html

answered Feb 14, 2019 at 1:24

sunny0402's user avatar

sunny0402sunny0402

911 silver badge2 bronze badges

I use MinGW tool set which provides mingw32-make build tool, if you have it in your PATH system variables, in Windows Command Prompt just go into the directory containing the files and type this command:

mingw32-make -f Makefile.win

and it’s done.

answered Jun 27, 2020 at 15:55

WENDYN's user avatar

WENDYNWENDYN

5916 silver badges14 bronze badges

1

I tried all of the above. What helps me:

  1. Download the mingw-get.
  2. Setup it.
  3. Add something like this C:MinGWbin to environment variables.
  4. Launch (!important) git bash. Power shell, developer vs cmd, system cmd etc didn’t help.
  5. Type mingw-get into the command line.
  6. After type mingw-get install mingw32-make.

Done! Now You might be able to use make-commands from any folder that contains Makefile.

Ashish Kankal's user avatar

answered Jan 25, 2021 at 16:53

binary robot's user avatar

0

With Visual Studio 2017 I had to add this folder to my Windows 10 path env variable:

C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.10.25017binHostX64x64

There’s also HostX86

answered Apr 24, 2017 at 13:01

Jón Trausti Arason's user avatar

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.win (the .win suffix) indicates it’s a makefile compatible with Windows NMake. So you could try nmake -f Makefile.win.

Often standard Linux Makefiles are provided and NMake looks promising. However, the following link takes a simple Linux Makefile and explains some fundamental issues that one may encounter. It also suggests a few alternatives to handling Linux Makefiles on Windows.

Makefiles in Windows

answered Dec 2, 2015 at 6:00

ap-osd's user avatar

ap-osdap-osd

2,46916 silver badges16 bronze badges

Firstly, add path of visual studio common tools (c:Program Files (x86)Microsoft Visual Studio 14.0Common7Tools) into the system path. To learn how to add a path into system path, please check this website:
http://www.computerhope.com/issues/ch000549.htm. You just need to this once.

After that, whenever you need, open a command line and execute vsvars32.bat to add all required visual studio tools’ paths into the system path.

Then, you can call nmake -f makefile.mak

PS: Path of visual studio common tools might be different in your system. Please change it accordingly.

answered Oct 26, 2015 at 13:59

Validus Oculus's user avatar

Validus OculusValidus Oculus

2,5881 gold badge24 silver badges33 bronze badges

Install msys2 with make dependency add both to PATH variable.
(The second option is GNU ToolChain for Windows. MinGW version has already mingw32-make included.)

Install Git Bash. Run mingw32-make from Git Bash.

answered Feb 10, 2021 at 16:17

Liam Kernighan's user avatar

Liam KernighanLiam Kernighan

2,2471 gold badge21 silver badges23 bronze badges

1

If you have already installed the Windows GNU compiler (MinGW) from MSYS2 then make command comes pre-installed as wingw32-make. Always match cmake makefile generation with the correct make command. Mixing these generate problems.

MinGW makefile generation with MinGW make command

Visual Studio makefile generation with VS equivalent make command

And this is always possible as long as you have the source code. Just delete old build directory and start over by specifying this time the right parameter in cmake ,e.g.

mkdir build
cd build
cmake -G "MinGW MakeFiles" path/to/src/whereCMakeLists.txtInstructionsAre   
mingw32-make     
myProject.exe   # RUN

I have encountered issues during compilation where multiple make commands interact. To prevent this just edit/remove the environmental variables that lead to different make commands. For example to prevent conflicts with mingw, keep only C:msys64mingw64bin but remove C:msys64usrbin. That other path contains the msys make and as I said you do not want to combine make commands during compilation.

answered Jun 14, 2022 at 5:09

Bryan Laygond's user avatar

So if you’re using Vscode and Mingw then you should first make sure that the bin folder of the mingw is included in the environment path and it is preferred to change the mingw32-make.exe to make to ease the task and then create a makefile
and include this code in it .

all:
    gcc -o filename filename.c
    ./filename

Then save the makefile and open Vscode Code terminal and write make. Then makefile will get executed.

answered Dec 30, 2020 at 14:11

Lovish Garg's user avatar

1

I am assuming you added mingw32/bin is added to environment variables else please add it and I am assuming it as gcc compiler and you have mingw installer.

First step: download mingw32-make.exe from mingw installer, or please check mingw/bin folder first whether mingw32-make.exe exists or not, else than install it, rename it to make.exe.

After renaming it to make.exe, just go and run this command in the directory where makefile is located. Instead of renaming it you can directly run it as mingw32-make.

After all, a command is just exe file or a software, we use its name to execute the software, we call it as command.

Anatoly's user avatar

Anatoly

19.4k3 gold badges25 silver badges41 bronze badges

answered Dec 3, 2020 at 16:13

Bheem's user avatar

BheemBheem

212 bronze badges

For me installing ubuntu WSL on windows was the best option, that is the best tool for compiling makefile on windows. One thousand is better than Cygwin64, because to compile a makefile you will need another package and compile software like maybe gfortran, netcdf, etc, ect, in ubuntu WSL you can install all of these packages very easily and quickly ;)

answered Oct 14, 2022 at 15:16

mapiedrahitao's user avatar

1

The procedure I followed is;

  1. I installed Gnuwin32’s make using the installable.
  2. Added the «make» path to the environmental variable PATH.
  3. Verified the installation using «make —version»

answered Nov 10, 2022 at 11:57

Bhuvan's user avatar

BhuvanBhuvan

3288 bronze badges

1

May be it can work.

pip install Makefile

answered Jun 10, 2021 at 11:22

Nikhil Parashar's user avatar

I have some demos that I downloaded and they come with a Makefile.win and a Makefile.sgi. How can I run these in Windows to compile the demos?

0x6B6F77616C74's user avatar

asked Mar 28, 2010 at 7:48

Kim's user avatar

8

You can install GNU make with chocolatey, a well-maintained package manager, which will add make to the global path and runs on all CLIs (powershell, git bash, cmd, etc…) saving you a ton of time in both maintenance and initial setup to get make running.

  1. Install the chocolatey package manager for Windows
    compatible to Windows 7+ / Windows Server 2003+

  2. Run choco install make

I am not affiliated with choco, but I highly recommend it, so far it has never let me down and I do have a talent for breaking software unintentionally.

answered Jul 15, 2019 at 15:05

ledawg's user avatar

ledawgledawg

2,1351 gold badge11 silver badges17 bronze badges

2

If you have Visual Studio, run the Visual Studio Command prompt from the Start menu, change to the directory containing Makefile.win and type this:

nmake -f Makefile.win

You can also use the normal command prompt and run vsvars32.bat (c:Program Files (x86)Microsoft Visual Studio 9.0Common7Tools for VS2008). This will set up the environment to run nmake and find the compiler tools.

answered Mar 28, 2010 at 7:50

Marcelo Cantos's user avatar

Marcelo CantosMarcelo Cantos

179k38 gold badges324 silver badges363 bronze badges

16

Check out GnuWin’s make (for windows), which provides a native port for Windows (without requiring a full runtime environment like Cygwin)

If you have winget, you can install via the CLI like this:

winget install GnuWin32.Make

Also, be sure to add the install path to your system PATH:

C:Program Files (x86)GnuWin32bin

KyleMit's user avatar

KyleMit

36.5k63 gold badges440 silver badges635 bronze badges

answered Jun 6, 2013 at 13:41

Sean Lynch's user avatar

Sean LynchSean Lynch

6,1672 gold badges43 silver badges45 bronze badges

3

Check out cygwin, a Unix alike environment for Windows

answered Mar 28, 2010 at 7:50

Frank's user avatar

FrankFrank

2,32618 silver badges17 bronze badges

4

Here is my quick and temporary way to run a Makefile

  • download make from SourceForge: gnuwin32
  • install it
  • go to the install folder

C:Program Files (x86)GnuWin32bin

  • copy the all files in the bin to the folder that contains Makefile

libiconv2.dll libintl3.dll make.exe

  • open the cmd (you can do it with right click with shift) in the folder that contains Makefile and run

make.exe

done.

Plus, you can add arguments after the command, such as

make.exe skel

Maria Ines Parnisari's user avatar

answered Oct 20, 2017 at 3:59

alan9uo's user avatar

alan9uoalan9uo

97111 silver badges16 bronze badges

4

If you install Cygwin. Make sure to select make in the installer. You can then run the following command provided you have a Makefile.

make -f Makefile

https://cygwin.com/install.html

answered Feb 14, 2019 at 1:24

sunny0402's user avatar

sunny0402sunny0402

911 silver badge2 bronze badges

I use MinGW tool set which provides mingw32-make build tool, if you have it in your PATH system variables, in Windows Command Prompt just go into the directory containing the files and type this command:

mingw32-make -f Makefile.win

and it’s done.

answered Jun 27, 2020 at 15:55

WENDYN's user avatar

WENDYNWENDYN

5916 silver badges14 bronze badges

1

I tried all of the above. What helps me:

  1. Download the mingw-get.
  2. Setup it.
  3. Add something like this C:MinGWbin to environment variables.
  4. Launch (!important) git bash. Power shell, developer vs cmd, system cmd etc didn’t help.
  5. Type mingw-get into the command line.
  6. After type mingw-get install mingw32-make.

Done! Now You might be able to use make-commands from any folder that contains Makefile.

Ashish Kankal's user avatar

answered Jan 25, 2021 at 16:53

binary robot's user avatar

0

With Visual Studio 2017 I had to add this folder to my Windows 10 path env variable:

C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.10.25017binHostX64x64

There’s also HostX86

answered Apr 24, 2017 at 13:01

Jón Trausti Arason's user avatar

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.win (the .win suffix) indicates it’s a makefile compatible with Windows NMake. So you could try nmake -f Makefile.win.

Often standard Linux Makefiles are provided and NMake looks promising. However, the following link takes a simple Linux Makefile and explains some fundamental issues that one may encounter. It also suggests a few alternatives to handling Linux Makefiles on Windows.

Makefiles in Windows

answered Dec 2, 2015 at 6:00

ap-osd's user avatar

ap-osdap-osd

2,46916 silver badges16 bronze badges

Firstly, add path of visual studio common tools (c:Program Files (x86)Microsoft Visual Studio 14.0Common7Tools) into the system path. To learn how to add a path into system path, please check this website:
http://www.computerhope.com/issues/ch000549.htm. You just need to this once.

After that, whenever you need, open a command line and execute vsvars32.bat to add all required visual studio tools’ paths into the system path.

Then, you can call nmake -f makefile.mak

PS: Path of visual studio common tools might be different in your system. Please change it accordingly.

answered Oct 26, 2015 at 13:59

Validus Oculus's user avatar

Validus OculusValidus Oculus

2,5881 gold badge24 silver badges33 bronze badges

Install msys2 with make dependency add both to PATH variable.
(The second option is GNU ToolChain for Windows. MinGW version has already mingw32-make included.)

Install Git Bash. Run mingw32-make from Git Bash.

answered Feb 10, 2021 at 16:17

Liam Kernighan's user avatar

Liam KernighanLiam Kernighan

2,2471 gold badge21 silver badges23 bronze badges

1

If you have already installed the Windows GNU compiler (MinGW) from MSYS2 then make command comes pre-installed as wingw32-make. Always match cmake makefile generation with the correct make command. Mixing these generate problems.

MinGW makefile generation with MinGW make command

Visual Studio makefile generation with VS equivalent make command

And this is always possible as long as you have the source code. Just delete old build directory and start over by specifying this time the right parameter in cmake ,e.g.

mkdir build
cd build
cmake -G "MinGW MakeFiles" path/to/src/whereCMakeLists.txtInstructionsAre   
mingw32-make     
myProject.exe   # RUN

I have encountered issues during compilation where multiple make commands interact. To prevent this just edit/remove the environmental variables that lead to different make commands. For example to prevent conflicts with mingw, keep only C:msys64mingw64bin but remove C:msys64usrbin. That other path contains the msys make and as I said you do not want to combine make commands during compilation.

answered Jun 14, 2022 at 5:09

Bryan Laygond's user avatar

So if you’re using Vscode and Mingw then you should first make sure that the bin folder of the mingw is included in the environment path and it is preferred to change the mingw32-make.exe to make to ease the task and then create a makefile
and include this code in it .

all:
    gcc -o filename filename.c
    ./filename

Then save the makefile and open Vscode Code terminal and write make. Then makefile will get executed.

answered Dec 30, 2020 at 14:11

Lovish Garg's user avatar

1

I am assuming you added mingw32/bin is added to environment variables else please add it and I am assuming it as gcc compiler and you have mingw installer.

First step: download mingw32-make.exe from mingw installer, or please check mingw/bin folder first whether mingw32-make.exe exists or not, else than install it, rename it to make.exe.

After renaming it to make.exe, just go and run this command in the directory where makefile is located. Instead of renaming it you can directly run it as mingw32-make.

After all, a command is just exe file or a software, we use its name to execute the software, we call it as command.

Anatoly's user avatar

Anatoly

19.4k3 gold badges25 silver badges41 bronze badges

answered Dec 3, 2020 at 16:13

Bheem's user avatar

BheemBheem

212 bronze badges

For me installing ubuntu WSL on windows was the best option, that is the best tool for compiling makefile on windows. One thousand is better than Cygwin64, because to compile a makefile you will need another package and compile software like maybe gfortran, netcdf, etc, ect, in ubuntu WSL you can install all of these packages very easily and quickly ;)

answered Oct 14, 2022 at 15:16

mapiedrahitao's user avatar

1

The procedure I followed is;

  1. I installed Gnuwin32’s make using the installable.
  2. Added the «make» path to the environmental variable PATH.
  3. Verified the installation using «make —version»

answered Nov 10, 2022 at 11:57

Bhuvan's user avatar

BhuvanBhuvan

3288 bronze badges

1

May be it can work.

pip install Makefile

answered Jun 10, 2021 at 11:22

Nikhil Parashar's user avatar


Я следую инструкциям человека, репозиторий которого я клонировал на свою машину. Я хочу просто: иметь возможность использовать makeкоманду как часть настройки среды кода. Но я использую Windows и поискал в Интернете только файл make.exe для загрузки, make-4.1.tar.gzфайл для загрузки (я не знаю, что с ним делать дальше) и кое-что о загрузке MinGW (для GNU; но после установки я не нашел упоминания о «make»).

Мне не нужен компилятор GNU или подобные вещи; Я хочу использовать только make в Windows. Скажите, пожалуйста, что мне нужно сделать для этого?

Заранее спасибо!


Ответы:


make— это команда GNU, поэтому единственный способ получить ее в Windows — это установить версию Windows, подобную той, которая предоставляется GNUWin32 . Или вы можете установить MinGW, а затем сделать:

copy c:MinGWbinmingw32-make.exe c:MinGWbinmake.exe

или создайте ссылку на фактический исполняемый файл в своем PATH. В этом случае при обновлении MinGW ссылка не удаляется:

mklink c:binmake.exe C:MinGWbinmingw32-make.exe

Другой вариант — использовать Chocolatey . Сначала вам нужно установить этот менеджер пакетов. После установки вам просто необходимо установить make:

choco install make

Последний вариант — это установка подсистемы Windows для Linux (WSL) , поэтому у вас будет выбранный вами дистрибутив Linux, встроенный в Windows 10, куда вы сможете установить make, gccи все инструменты, необходимые для создания программ C.







GNU make доступен для шоколадного.

  • Установите шоколадный отсюда .

  • Тогда choco install make.

Теперь вы сможете использовать Make в Windows.
Я пробовал использовать его на MinGW, но он должен работать и на CMD.






Принятый ответ в целом является плохой идеей, потому что созданный вручную make.exeостанется неизменным и потенциально может вызвать неожиданные проблемы. На самом деле это нарушает работу RubyInstaller: https://github.com/oneclick/rubyinstaller2/issues/105

Альтернативой является установка make через Chocolatey (как указано @Vasantha Ganesh K)

Другой альтернативой является установка MSYS2 из Chocolatey и использование makeиз C:toolsmsys64usrbin. Если makeс MSYS2 не устанавливается автоматически, вам необходимо установить его вручную через pacman -S make(как указано @Thad Guidry и @Luke).




Если вы используете Windows 10, она встроена в подсистему Linux. Просто запустите командную строку Bash (нажмите клавишу Windows, затем введите bashи выберите «Bash в Ubuntu в Windows»), cdперейдите в каталог, который вы хотите создать, и введите make.

FWIW, диски Windows находятся /mnt, например, C:диск находится /mnt/cв Bash.

Если Bash недоступен из меню «Пуск», вот инструкции по включению этой функции Windows (только для 64-разрядной версии Windows):

https://docs.microsoft.com/en-us/windows/wsl/install-win10




  1. Установите Msys2 http://www.msys2.org
  2. Следуйте инструкциям по установке
  3. Установите make с помощью$ pacman -S make gettext base-devel
  4. Добавить C:msys64usrbinна свой путь

Скачайте make.exe с их официального сайта GnuWin32

  • В сеансе загрузки щелкните
    Полный пакет, кроме источников .

  • Следуйте инструкциям по установке.

  • По завершении добавьте <installation directory>/bin/в переменную PATH.

Теперь вы сможете использовать make в cmd.



Другой альтернативой является то, что если вы уже установили minGW и добавили папку bin в переменную среды Path, вы можете использовать «mingw32-make» вместо «make».

Вы также можете создать символическую ссылку от «make» к «mingw32-make» или скопировать и изменить имя файла. Я бы не рекомендовал эти варианты раньше, они будут работать, пока вы не внесете изменения в minGW.



Могу предложить пошаговый подход.

  1. Посетите GNUwin
  2. Загрузите программу установки
  3. Следуйте инструкциям и установите GNUWin. Обратите внимание на каталог, в который устанавливается ваше приложение. (Вам понадобится позже1)
  4. Следуйте этим инструкциям и добавьте make в переменные среды. Как я уже говорил вам раньше, теперь пора узнать, где было установлено ваше приложение. К вашему сведению: каталог по умолчанию C:Program Files (x86)GnuWin32.
  5. Теперь обновите PATH, чтобы включить каталог bin недавно установленной программы. Типичный пример того, что можно добавить к пути:...;C:Program Files (x86)GnuWin32bin

Одно из решений, которое может оказаться полезным, если вы хотите использовать эмулятор командной строки cmder. Вы можете установить установщик пакетов по отдельности. Сначала мы устанавливаем по очереди в командной строке Windows, используя следующую строку:

@"%SystemRoot%System32WindowsPowerShellv1.0powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin"
refreshenv

После установки chocolatey можно использовать команду choco для установки make. После установки вам нужно будет добавить псевдоним в /cmder/config/user_aliases.cmd. Следует добавить следующую строку:

make="path_to_chocolateychocolateybinmake.exe" $*

После этого Make будет работать в среде cmder.

Установка утилиты make в Windows

Если сразу после установки Windows не видит make, перезапустите программу, из которой запускаете его [make], а лучше перезагрузите ОС.

Вообще, пока что в Makefile нет необходимости, т.к. ничего нет. :) Но думаю, что скоро без него собирать будет проблематично.

Первый способ: порт GnuMake

Скачайте и установите порт GnuMake (все настройки на ваше усмотрение). Добавьте в системную переменную PATH <путь до установки GnuMake>bin. Например C:GnuWin32bin.

Второй способ: портированный make через Cygwin

Предположительно, это самый простой вариант установки и последующего использования make.

Cygwin — это большая коллекция портированных программ проекта GNU и некоторых других Open Source решений. Не имеет возможности работы с нативными Linux приложениями.

Скачайте установщик Cygwin. Далее проследуйте инструкциям инсталлятора. Можете поменять путь до директории установки, а так — везде далее. В открывшемся окне сверху в поле search введите make и немного подождите (enter НЕ нажимать). В разделе Devel выберете одну из версий утилиты make, нажав на её название, Next, дождитесь завершения установки. Добавьте в системную переменную PATH <путь до установки Cygwin>bin. Например C:Program Files (x86)cygwin64bin.

Третий способ (для владельцев 64-битных Windows 10): WSL

Если у вас установлено обновление Fall Creators Update, выполните инструкцию по ссылке (советую для простоты Ubuntu). Далее через меню «Пуск» запустите установленный дистрибутив (Ubuntu). После установите требуемые пакеты (если вы выбрали не Ubuntu, то сами знаете, что делать):

sudo apt-get update
sudo apt-get install make golang

Всё, у вас немного урезанный Linux на Windows. Без виртуальных машин. Быстрее, проще и удобнее. :)

Для тех, у кого Anniversary Update — инструкция тут. Далее те же действия, что и после ссылки для Fall Creators Update.

Если не знаете, какое у вас обновление и Windows постоянно что-то устанавливает и иногда просит перезагрузиться, то у вас Fall Creators Update — смотрите первую инструкцию.

Четвёртый способ: окружение MinGW

MinGW — Linux-подобное окружение, предоставляющее доступ к программам GNU и некоторым другим проектам из Open Source.

Скачайте установщик MinGW и следуйте инструкциям инсталлятора. Можете поменять путь до директории установки, остальное по желанию. В появившемся окне выбрать mingw32-base Mark for installation, в меню Installation -> Update Catalogue. После окончания установки закройте окно. Добавьте в системную переменную PATH <путь до установки MinGW>bin. Например C:MinGWbin. После этого сделайте дубликат файла mingw32-make.exe в той же директории и переименуйте его [дубликат] в make.exe.

Учтите что по-умолчанию у вас на выходе будут исполняемые файлы Linux, но MinGW не позволяет их запускать, так что нужно явно указывать, что компилировать для Windows.

Пятый способ: nmake (не рекомендуется)

Не рекомендуется к применению для данного проекта. Только если вы ПОНИМАЕТЕ, что делаете, т.к. текущий Makefile не совместим с nmake.

Утилита nmake встроена в пакет средств для Visual C++. Он входит в состав Visual Studio, и если вы её [Visual Studio] никогда не устанавливали, то можете просто установить себе этот пакет отдельно. Пропишите в системную переменную PATH (если ещё этого не умеете, то тут всё объясняется) путь до папки с бинарными файлами пакета (обычно это C:Program Files (x86)Microsoft Visual Studio 14.0VCbin).

Далее аналогично использованию make в Linux, только вместо make использовать nmake.

У nmake есть некоторые отличия от make. В основном, они касаются порядка запуска целей и операторов с точкой (типа .PHONY). Учитывайте это. Могут быть различия в некоторых оператарах.

Шестой способ: сборка в Docker

Если вы очень смелый и всё выше описанное слишком просто для вас, то можно исходники собирать прямо в Docker (ссылочка на Docker). Здесь описана общая суть подобного процесса.

Седьмой способ: Linux

Надо было ставить Linux

Восьмой способ: виртуальная машина

Советую лишь на САМЫЙ крайний случай, когда всё остальное не работает, а установить Linux нет возможности. Вот стороннее приложение VirtualBox, а вот включение и настройка встроенного механизма Hyper-V (только для корпоративных и профессиональных версий Windows).

Понравилась статья? Поделить с друзьями:
  • Как запустить mount and blade warband на windows 10
  • Как запустить magicka на windows 10
  • Как запустить mafia the city of lost heaven на windows 10
  • Как запустить mafia definitive edition под windows 7
  • Как запустить mongodb сервер на windows