Как использовать makefile в visual studio
I have just downloaded a open source project which is said to be compiled using visual studio c++. It contains 3 makeFiles (makeFile, makeFile(1) and makeFile(2) ) I always open programs in VS using the .sln files and now I dont know what to do with this makeFile. can anyone instruct me how to deal with it please.
Without seeing the actual makefiles it's hard to say but first I would try this, menu File/New/Project . Select makefile project
Did you try following the instructions that came with the download? It would help a lot to include at least the name of the project.
4 Answers 4
NMake is included with Visual Studio. You may try with NMake shipped with the edition of Visual Studio you may want to use.
-1: He may or may not have Googled it, but I did, and this was the top result. Your answer was helpful to me and no doubt anyone else with the same question, but it would have been equally helpful without the attitude :)
@Ozzah, I didn't mean to show any attitude. I was just being curious if the asker has Googled and has found anything. I understand that questions like these are more suited in comments rather than in answers. Thanks for pointing this out. I have edited my answer.
If you are only familiar with Visual Studio projects and solutions, dealing with makefiles can be a challenge. The following link will give you a good introduction to makefiles from a Visual studio perspective.
Translating Linux makefiles to Visual Studio solution will be a manual effort.
NMake looks promising. However, the following link takes a simple Makefile and explains some fundamental issues that one may encounter.
VS2017 and cross-platform dev with make linux binaries
If you're working on windows 10, you can make make work and compile linux binaries:
have lxss installed, and gdb server, ssh server installed:
sudo apt update && sudo apt install -y build-essential gdbserver openssh-server
make sure you can connect through ssh to your local machine:
sudo vi /etc/ssh/sshd_config && sudo service ssh start
make sure you have linux development with c++ packages installed (VS2017 install)
make sure you configured your connexion to lsxx through ssh in VS/tools/options/connection manager ("connection" in search).
make sure to have a linux project (new project/other languages/vc++/crossplatform/linux)
Makefile — это текстовый файл, содержащий инструкции по компиляции и компоновке (или сборке) набора файлов исходного кода. Программа (часто называемая программой make ) считывает файл makefile и вызывает компилятор, компоновщик и, возможно, другие программы для создания исполняемого файла. Программа Майкрософт называется NMAKE.
Если у вас есть проект makefile, у вас есть следующие варианты, если вы хотите изменить, выполнить сборку и отладку в интегрированной среде разработки Visual Studio:
- Создайте в Visual Studio проект makefile, который использует существующий файл makefile для настройки файла VCXPROJ, используемого средой Visual Studio для IntelliSense. (У вас не будут все функции интегрированной среды разработки, которые вы получаете с помощью собственного проекта MSBuild.) См. раздел "Создание проекта makefile" ниже.
- Используйте мастер создания нового проекта из существующих файлов кода, чтобы создать собственный проект MSBuild из исходного кода. Исходный файл makefile больше не будет использоваться. Дополнительные сведения см. в разделе Практическое руководство. Создание проекта C++ из существующего кода.
- Visual Studio 2017 и более поздних версий: используйте функцию "Открыть папку", чтобы изменить и создать проект makefile "как есть" без участия системы MSBuild. Дополнительные сведения см. в статье Проекты "Открыть папку" для C++.
- Visual Studio 2019 и более поздних версий: создайте проект makefile UNIX для Linux.
Создание проекта makefile с использованием шаблона проекта makefile
В Visual Studio 2017 и более поздних версиях шаблон проекта Makefile доступен, если установлена рабочая нагрузка разработки классических приложений на C++.
Используйте мастер, чтобы указать команды и среду, используемые файлом makefile. Затем этот проект можно использовать для сборки кода в Visual Studio.
По умолчанию проект makefile не отображает в обозревателе решений никаких файлов. Проект makefile задает параметры сборки, которые показаны на странице свойств проекта.
Выходной файл, указанный в проекте, не влияет на имя, создаваемое скриптом сборки. Он объявляет только намерение. Файл makefile по-прежнему управляет процессом сборки и указывает ее целевые объекты.
Создание проекта makefile в Visual Studio
В главном меню Visual Studio выберите FileNew> >Project и в поле поиска введите makefile. Если отображается несколько шаблонов проекта, выберите один из вариантов в зависимости от целевой платформы.
Создание проекта makefile в Visual Studio 2015 или Visual Studio 2017
На начальной странице Visual Studio введите строку "makefile" в поле поиска Новый проект. Или же откройте диалоговое окно Новый проект, разверните узел Visual C++>Общие (Visual Studio 2015) или Прочие (Visual Studio 2017) и в области шаблонов выберите Проект Makefile, чтобы открыть мастер проектов.
На странице Параметры приложения предоставьте сведения о команде, выводе, удалении и перестроении для отладочной и окончательной сборок.
На этой странице свойств можно просматривать и изменять свойства проекта. Дополнительные сведения о отображении страницы свойств см. в разделе Set C++ compiler and build properties in Visual Studio.
Мастер проекта makefile
Создав проект makefile, вы можете просматривать и изменять каждый из следующих параметров на странице Nmake свойств проекта.
Командная строка сборки: Указывает командную строку, выполняемую при выборе пользователем команды "Сборка" в меню "Сборка". Отображается в поле "Командная строка для сборки" на странице "Nmake" свойств проекта.
Выход: Указывает имя файла, который будет содержать выходные данные командной строки. По умолчанию этот параметр основан на имени проекта. Отображается в поле "Вывод" на странице "Nmake" свойств проекта.
Команды очистки: Указывает командную строку, выполняемую, когда пользователь нажимает кнопку "Очистить" в меню "Сборка". Отображается в поле "Командная строка для очистки" на странице "Nmake" свойств проекта.
Перестройте командную строку: Указывает командную строку, выполняемую, когда пользователь выбирает перестроение из меню "Сборка". Отображается в поле "Командная строка для перестроения всех файлов" на странице "Nmake" свойств проекта.
Практическое руководство. Использование IntelliSense для проекта Makefile
IntelliSense не работает в проектах makefile, если определенные параметры проекта или компилятора заданы неправильно. Чтобы настроить проекты makefile для правильной работы IntelliSense, выполните указанные ниже действия.
Выберите страницу свойств ConfigurationPropertiesNMake>.
Измените свойства в IntelliSense соответствующим образом:
Задайте свойство Определения препроцессора, чтобы определить символы препроцессора в проекте makefile. Дополнительные сведения см. в разделе /D (Определения препроцессора).
Задайте свойство Путь поиска включаемых файлов, чтобы указать список каталогов, где компилятор будет производить поиск для разрешения ссылок на файлы, передаваемых в директивы препроцессора в новом проекте makefile. Дополнительные сведения см. в разделе /I (Дополнительные каталоги включения).
Для проектов, созданных с использованием CL.EXE из командного окна, задайте переменную среды INCLUDE, чтобы указать каталоги, где компилятор будет производить поиск для разрешения ссылок на файлы, передаваемых в директивы препроцессора в новом проекте makefile.
Задайте свойство Принудительно включаемые файлы, чтобы указать файлы заголовков, обрабатываемые при сборке проекта makefile. Дополнительные сведения см. в разделе /FI (Имя принудительного включения файла).
Задайте свойство "Дополнительные параметры" , чтобы указать другие параметры компилятора, которые будут использоваться IntelliSense при анализе файлов C++.
Используйте команду Сохранить все, чтобы сохранить измененные параметры проекта.
При следующем открытии проекта makefile в среде разработки Visual Studio запустите команду Очистить решение, а затем — команду Собрать решение для проекта makefile. Технология IntelliSense должна работать в интегрированной среде разработки правильно.
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.
To create a makefile project with the makefile project template
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 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.
Makefile — это текстовый файл, содержащий инструкции по компиляции и компоновке (или сборке) набора файлов исходного кода. Программа (часто называемая программой make ) считывает файл makefile и вызывает компилятор, компоновщик и, возможно, другие программы для создания исполняемого файла. Программа Майкрософт называется NMAKE.
Если у вас есть проект makefile, у вас есть следующие варианты, если вы хотите изменить, выполнить сборку и отладку в интегрированной среде разработки Visual Studio:
- Создайте в Visual Studio проект makefile, который использует существующий файл makefile для настройки файла VCXPROJ, используемого средой Visual Studio для IntelliSense. (У вас не будут все функции интегрированной среды разработки, которые вы получаете с помощью собственного проекта MSBuild.) См. раздел "Создание проекта makefile" ниже.
- Используйте мастер создания нового проекта из существующих файлов кода, чтобы создать собственный проект MSBuild из исходного кода. Исходный файл makefile больше не будет использоваться. Дополнительные сведения см. в разделе Практическое руководство. Создание проекта C++ из существующего кода.
- Visual Studio 2017 и более поздних версий: используйте функцию "Открыть папку", чтобы изменить и создать проект makefile "как есть" без участия системы MSBuild. Дополнительные сведения см. в статье Проекты "Открыть папку" для C++.
- Visual Studio 2019 и более поздних версий: создайте проект makefile UNIX для Linux.
Создание проекта makefile с использованием шаблона проекта makefile
В Visual Studio 2017 и более поздних версиях шаблон проекта Makefile доступен, если установлена рабочая нагрузка разработки классических приложений на C++.
Используйте мастер, чтобы указать команды и среду, используемые файлом makefile. Затем этот проект можно использовать для сборки кода в Visual Studio.
По умолчанию проект makefile не отображает в обозревателе решений никаких файлов. Проект makefile задает параметры сборки, которые показаны на странице свойств проекта.
Выходной файл, указанный в проекте, не влияет на имя, создаваемое скриптом сборки. Он объявляет только намерение. Файл makefile по-прежнему управляет процессом сборки и указывает ее целевые объекты.
Создание проекта makefile в Visual Studio
В главном меню Visual Studio выберите FileNew> >Project и в поле поиска введите makefile. Если отображается несколько шаблонов проекта, выберите один из вариантов в зависимости от целевой платформы.
Создание проекта makefile в Visual Studio 2015 или Visual Studio 2017
На начальной странице Visual Studio введите строку "makefile" в поле поиска Новый проект. Или же откройте диалоговое окно Новый проект, разверните узел Visual C++>Общие (Visual Studio 2015) или Прочие (Visual Studio 2017) и в области шаблонов выберите Проект Makefile, чтобы открыть мастер проектов.
На странице Параметры приложения предоставьте сведения о команде, выводе, удалении и перестроении для отладочной и окончательной сборок.
На этой странице свойств можно просматривать и изменять свойства проекта. Дополнительные сведения о отображении страницы свойств см. в разделе Set C++ compiler and build properties in Visual Studio.
Мастер проекта makefile
Создав проект makefile, вы можете просматривать и изменять каждый из следующих параметров на странице Nmake свойств проекта.
Командная строка сборки: Указывает командную строку, выполняемую при выборе пользователем команды "Сборка" в меню "Сборка". Отображается в поле "Командная строка для сборки" на странице "Nmake" свойств проекта.
Выход: Указывает имя файла, который будет содержать выходные данные командной строки. По умолчанию этот параметр основан на имени проекта. Отображается в поле "Вывод" на странице "Nmake" свойств проекта.
Команды очистки: Указывает командную строку, выполняемую, когда пользователь нажимает кнопку "Очистить" в меню "Сборка". Отображается в поле "Командная строка для очистки" на странице "Nmake" свойств проекта.
Перестройте командную строку: Указывает командную строку, выполняемую, когда пользователь выбирает перестроение из меню "Сборка". Отображается в поле "Командная строка для перестроения всех файлов" на странице "Nmake" свойств проекта.
Практическое руководство. Использование IntelliSense для проекта Makefile
IntelliSense не работает в проектах makefile, если определенные параметры проекта или компилятора заданы неправильно. Чтобы настроить проекты makefile для правильной работы IntelliSense, выполните указанные ниже действия.
Выберите страницу свойств ConfigurationPropertiesNMake>.
Измените свойства в IntelliSense соответствующим образом:
Задайте свойство Определения препроцессора, чтобы определить символы препроцессора в проекте makefile. Дополнительные сведения см. в разделе /D (Определения препроцессора).
Задайте свойство Путь поиска включаемых файлов, чтобы указать список каталогов, где компилятор будет производить поиск для разрешения ссылок на файлы, передаваемых в директивы препроцессора в новом проекте makefile. Дополнительные сведения см. в разделе /I (Дополнительные каталоги включения).
Для проектов, созданных с использованием CL.EXE из командного окна, задайте переменную среды INCLUDE, чтобы указать каталоги, где компилятор будет производить поиск для разрешения ссылок на файлы, передаваемых в директивы препроцессора в новом проекте makefile.
Задайте свойство Принудительно включаемые файлы, чтобы указать файлы заголовков, обрабатываемые при сборке проекта makefile. Дополнительные сведения см. в разделе /FI (Имя принудительного включения файла).
Задайте свойство "Дополнительные параметры" , чтобы указать другие параметры компилятора, которые будут использоваться IntelliSense при анализе файлов C++.
Используйте команду Сохранить все, чтобы сохранить измененные параметры проекта.
При следующем открытии проекта makefile в среде разработки Visual Studio запустите команду Очистить решение, а затем — команду Собрать решение для проекта makefile. Технология IntelliSense должна работать в интегрированной среде разработки правильно.
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.
To create a makefile project with the makefile project template
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 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.
Читайте также: