Как запустить makefile в windows
Перейти к содержимому

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

  • автор:

Makefile: что это, как запустить Makefile на Linux и на Windows

Lorem ipsum dolor

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

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

$ make

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

$ make <имя цели>

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

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

nmake -f Makefile.win

Заключение

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

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Makefile для самых маленьких

Не очень строгий перевод материала mrbook.org/tutorials/make Мне в свое время очень не хватило подобной методички для понимания базовых вещей о make. Думаю, будет хоть кому-нибудь интересно. Хотя эта технология и отмирает, но все равно используется в очень многих проектах. Кармы на хаб «Переводы» не хватило, как только появится возможность — добавлю и туда. Добавил в Переводы. Если есть ошибки в оформлении, то прошу указать на них. Буду исправлять.

Статья будет интересная прежде всего изучающим программирование на C/C++ в UNIX-подобных системах от самых корней, без использования IDE.

Компилировать проект ручками — занятие весьма утомительное, особенно когда исходных файлов становится больше одного, и для каждого из них надо каждый раз набивать команды компиляции и линковки. Но не все так плохо. Сейчас мы будем учиться создавать и использовать Мейкфайлы. Makefile — это набор инструкций для программы make, которая помогает собирать программный проект буквально в одно касание.

Для практики понадобится создать микроскопический проект а-ля Hello World из четырех файлов в одном каталоге:

Все скопом можно скачать отсюда
Автор использовал язык C++, знать который совсем не обязательно, и компилятор g++ из gcc. Любой другой компилятор скорее всего тоже подойдет. Файлы слегка подправлены, чтобы собирались gcc 4.7.1

Программа make

Если запустить
make
то программа попытается найти файл с именем по умолчание Makefile в текущем каталоге и выполнить инструкции из него. Если в текущем каталоге есть несколько мейкфайлов, то можно указать на нужный вот таким образом:
make -f MyMakefile
Есть еще множество других параметров, нам пока не нужных. О них можно узнать в ман-странице.

Процесс сборки

Компилятор берет файлы с исходным кодом и получает из них объектные файлы. Затем линковщик берет объектные файлы и получает из них исполняемый файл. Сборка = компиляция + линковка.

Компиляция руками

Самый простой способ собрать программу:
g++ main.cpp hello.cpp factorial.cpp -o hello
Каждый раз набирать такое неудобно, поэтому будем автоматизировать.

Самый простой Мейкфайл

В нем должны быть такие части:

Для нашего примера мейкфайл будет выглядеть так:

Обратите внимание, что строка с командой должна начинаться с табуляции! Сохраните это под именем Makefile-1 в каталоге с проектом и запустите сборку командой make -f Makefile-1
В первом примере цель называется all . Это цель по умолчанию для мейкфайла, которая будет выполняться, если никакая другая цель не указана явно. Также у этой цели в этом примере нет никаких зависимостей, так что make сразу приступает к выполнению нужной команды. А команда в свою очередь запускает компилятор.

Использование зависимостей

Использовать несколько целей в одном мейкфайле полезно для больших проектов. Это связано с тем, что при изменении одного файла не понадобится пересобирать весь проект, а можно будет обойтись пересборкой только измененной части. Пример:

Это надо сохранить под именем Makefile-2 все в том же каталоге

Теперь у цели all есть только зависимость, но нет команды. В этом случае make при вызове последовательно выполнит все указанные в файле зависимости этой цели.
Еще добавилась новая цель clean . Она традиционно используется для быстрой очистки всех результатов сборки проекта. Очистка запускается так: make -f Makefile-2 clean

Использование переменных и комментариев

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

Это Makefile-3
Переменные — очень удобная штука. Для их использования надо просто присвоить им значение до момента их использования. После этого можно подставлять их значение в нужное место вот таким способом: $(VAR)

Что делать дальше

После этого краткого инструктажа уже можно пробовать создавать простые мейкфайлы самостоятельно. Дальше надо читать серьезные учебники и руководства. Как финальный аккорд можно попробовать самостоятельно разобрать и осознать такой универсальный мейкфайл, который можно в два касания адаптировать под практически любой проект:

How to Install and Use “Make” in Windows

Install and Use Make in Windows

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.

Table of Contents

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

type Y to agree cmd-command

run menu

environment-variables

new-options

variable-value

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

powershell-choco

install-choco-make

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

powershell-command

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.

    of MinGW-get-setup.exe.
    Install MinGW by opening the setup file.

install-mingw

install--mingw2

mingw-insatallation-package-setup

mingw-exe-file

environment-variables

mingw-path

new

type-location

windows-power-shell-command

How to use Make on Windows?

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

source code

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

Name already in use

cpp-docs / docs / build / reference / creating-a-makefile-project.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Create a C++ makefile project

A makefile is a text file that contains instructions for how to compile and link (or build) a set of source code files. A program (often called a make program) reads the makefile and invokes a compiler, linker, and possibly other programs to make an executable file. The Microsoft program is called NMAKE.

If you have an existing makefile project, you have these choices if you want to edit, build, and debug in the Visual Studio IDE:

  • Create a makefile project in Visual Studio that uses your existing makefile to configure a .vcxproj file that Visual Studio will use for IntelliSense. (You won’t have all the IDE features that you get with a native MSBuild project.) See To create a makefile project below.
  • Use the Create New Project from Existing Code Files wizard to create a native MSBuild project from your source code. The original makefile won’t be used anymore. For more information, see How to: Create a C++ Project from Existing Code.
  • Visual Studio 2017 and later: Use the Open Folder feature to edit and build a makefile project as-is without any involvement of the MSBuild system. For more information, see Open Folder projects for C++.
  • Visual Studio 2019 and later: Create a UNIX makefile project for Linux.

In Visual Studio 2017 and later, the Makefile project template is available when the C++ Desktop Development workload is installed.

Follow the wizard to specify the commands and environment used by your makefile. You can then use this project to build your code in Visual Studio.

By default, the makefile project displays no files in Solution Explorer. The makefile project specifies the build settings, which are reflected in the project’s property page.

The output file that you specify in the project has no effect on the name that the build script generates. It declares only an intention. Your makefile still controls the build process and specifies the build targets.

To create a makefile project in Visual Studio

From the Visual Studio main menu, choose File > New > Project and type «makefile» into the search box. If you see more than one project template, select from the options depending on your target platform.

Windows only: In the Makefile project Debug Configuration Settings page, provide the command, output, clean, and rebuild information for debug and retail builds. Choose Next if you want to specify different settings for a Release configuration.

Choose Finish to close the dialog and open the newly created project in Solution Explorer.

To create a makefile project in Visual Studio 2015 or Visual Studio 2017

From the Visual Studio start page, type «makefile» in the New Project search box. Or, in the New Project dialog box, expand Visual C++ > General (Visual Studio 2015) or Other (Visual Studio 2017) and then select Makefile Project in the Templates pane to open the project wizard.

In the Application Settings page, provide the command, output, clean, and rebuild information for debug and retail builds.

Choose Finish to close the wizard and open the newly created project in Solution Explorer.

You can view and edit the project’s properties in its property page. For more information about displaying the property page, see Set C++ compiler and build properties in Visual Studio.

Makefile project wizard

After you create a makefile project, you can view and edit each of the following options in the Nmake page of the project’s property page.

Build command line: Specifies the command line to run when the user selects Build from the Build menu. Displayed in the Build command line field on the Nmake page of the project’s property page.

Output: Specifies the name of the file that will contain the output for the command line. By default, this option is based on the project name. Displayed in the Output field on the Nmake page of the project’s property page.

Clean commands: Specifies the command line to run when the user selects Clean from the Build menu. Displayed in the Clean command line field on the Nmake page of the project’s property page.

Rebuild command line: Specifies the command line to run when the user selects Rebuild from the Build menu. Displayed in the Rebuild all command line field on the Nmake page of the project’s property page.

How to: Enable IntelliSense for Makefile Projects

IntelliSense fails in makefile projects when certain project settings or compiler options are set up incorrectly. Follow these steps to configure makefile projects so that IntelliSense works as expected:

Open the Property Pages dialog box. For more information, see Set C++ compiler and build properties in Visual Studio.

Select the Configuration Properties > NMake property page.

Modify properties under IntelliSense as appropriate:

Set the Preprocessor Definitions property to define any preprocessor symbols in your makefile project. For more information, see /D (Preprocessor Definitions).

Set the Include Search Path property to specify the list of directories that the compiler will search to resolve file references that are passed to preprocessor directives in your makefile project. For more information, see /I (Additional Include Directories).

For projects that are built using CL.EXE from a Command Window, set the INCLUDE environment variable to specify directories that the compiler will search to resolve file references that are passed to preprocessor directives in your makefile project.

Set the Forced Includes property to specify which header files to process when building your makefile project. For more information, see /FI (Name Forced Include File).

Set the Assembly Search Path property to specify the list of directories that the compiler will search to resolve references to .NET assemblies in your project. For more information, see /AI (Specify Metadata Directories).

Set the Forced Using Assemblies property to specify which .NET assemblies to process when building your makefile project. For more information, see /FU (Name Forced #using File).

Set the Additional Options property to specify other compiler switches to be used by IntelliSense when parsing C++ files.

Choose OK to close the property pages.

Use the Save All command to save the modified project settings.

The next time you open your makefile project in the Visual Studio development environment, run the Clean Solution command and then the Build Solution command on your makefile project. IntelliSense should work properly in the IDE.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *