- Walkthrough: Working with Projects and Solutions (C++)
- Before you start
- Create a project
- To create a project in Visual Studio
- To create a project in Visual Studio 2017
- To create a project in Visual Studio 2015
- Organize projects and files
- To add a class to a project
- Add test code to your main function
- To add test code to the project
- Build and run your app project
- To build and run the project
- Пошаговое руководство: Создание стандартной программы C++ (C++)
- Предварительные требования
- Создание проекта и добавление исходного файла
- Создание проекта C++ в Visual Studio
- Создание проекта C++ в Visual Studio 2017
- Создание проекта C++ в Visual Studio 2015
- Добавление нового исходного файла
Walkthrough: Working with Projects and Solutions (C++)
Here’s how to create a C++ project in Visual Studio, add code, and then build and run the project. The project in this walkthrough is a program that tracks how many players are playing different card games.
In Visual Studio, work is organized in projects and solutions. A solution can have more than one project—for example, a DLL and an executable that references that DLL. For more information, see Solutions and Projects.
Before you start
To complete this walkthrough, you need Visual Studio 2017 or later. If you need a copy, here’s a short guide: Install C++ support in Visual Studio. If you haven’t done it yet, follow the next steps after installation through the «Hello, World» tutorial to make sure the C++ components are installed correctly and it all works.
It helps if you understand the fundamentals of the C++ language, and know what a compiler, linker, and debugger are used for. The tutorial also assumes that you’re familiar with Windows and how to use menus, dialogs,
Create a project
To create a project, first choose a project-type template. For each project type, Visual Studio sets compiler settings and—depending on the type—generates starter code that you can modify later. The following steps vary depending on which version of Visual Studio you’re using. To see the documentation for your preferred version of Visual Studio, use the Version selector control. It’s found at the top of the table of contents on this page.
To create a project in Visual Studio
- From the main menu, choose File >New >Project to open the Create a New Project dialog box.
- At the top of the dialog, set Language to C++, set Platform to Windows, and set Project type to Console.
- From the filtered list of project types, choose Console App then choose Next. In the next page, enter Game as the name for the project. You can accept the default location in the Location drop-down list, enter a different location, or choose the Browse button to browse to a directory where you want to save the project. When you create a project, Visual Studio puts the project in a solution. By default, the solution has the same name as the project. You can change the name in the Solution name box, but for this example, keep the default name.
- Choose the Create button to create the project. Visual Studio creates your new solution and project files, and opens the editor for the Game.cpp source code file it generated.
To create a project in Visual Studio 2017
- On the menu bar, choose File >New >Project.
- In the left pane of the New Project dialog box, expand Installed and select Visual C++, if it isn’t open already.
- In the list of installed templates in the center pane, select Console App.
- Enter a name for the project in the Name box. For this example, enter Game. You can accept the default location in the Location drop-down list, enter a different location, or choose the Browse button to browse to a directory where you want to save the project. When you create a project, Visual Studio puts the project in a solution. By default, the solution has the same name as the project. You can change the name in the Solution name box, but for this example, keep the default name.
- Choose the OK button to create the project. Visual Studio creates your new solution and project files, and opens the editor for the Game.cpp source code file it generated.
To create a project in Visual Studio 2015
- On the menu bar, choose File >New >Project.
- In the left pane of the New Project dialog box, expand Installed and select Visual C++, if it isn’t open already.
- In the list of installed templates in the center pane, select Win32 Console Application.
- Enter a name for the project in the Name box. For this example, enter Game. You can accept the default location in the Location drop-down list, enter a different location, or choose the Browse button to browse to a directory where you want to save the project. When you create a project, Visual Studio puts the project in a solution. By default, the solution has the same name as the project. You can change the name in the Solution name box, but for this example, keep the default name.
- Choose the OK button to dismiss the New Project dialog and start the Win32 Application Wizard.
- In the wizard, choose the Next button. On the Application Settings page, under Additional options, clear the Precompiled header check box.
- Choose the Finish button to create the project. Visual Studio creates your new solution and project files, and opens the editor for the Game.cpp source code file it generated.
Organize projects and files
You can use Solution Explorer to organize and manage the projects, files, and other resources in your solution.
This part of the walkthrough shows how to add a class to the project. When you add the class, Visual Studio adds the corresponding .h and .cpp files. You can see the results in Solution Explorer.
To add a class to a project
- If the Solution Explorer window isn’t displayed in Visual Studio, on the menu bar, choose View >Solution Explorer.
- In Solution Explorer, select the Game project. On the menu bar, choose Project >Add Class.
- In the Add Class dialog, enter Cardgame in the Class Name box. Don’t modify the default file names and settings. Choose the OK button. Visual Studio creates new files and adds them to your project. You can see them in the Solution Explorer window. Visual Studio opens the Cardgame.h and Cardgame.cpp files in the editor.
- Edit the Cardgame.h file, and make these changes:
- Add two private data members after the opening brace of the class definition.
int players; static int totalParticipants;
The Cardgame.h file should resemble this code after you change it:
#pragma once class Cardgame < int players; static int totalParticipants; public: Cardgame(int players); ~Cardgame(); static int GetParticipants() < return totalParticipants; >>;
The line #pragma once tells the compiler to include the header file only one time. For more information, see once . For information about other C++ keywords in the header file, see class , int , static , and public .
#include "Cardgame.h" #include using namespace std; int Cardgame::totalParticipants = 0; Cardgame::Cardgame(int players) : players(players) < totalParticipants += players; cout Cardgame::~Cardgame()
Note You can use auto-completion when you are entering code. For example, if you enter this code at the keyboard, you can enter pl or tot and then press Ctrl+Spacebar. Auto-completion enters players or totalParticipants for you.
Add test code to your main function
Add some code to your app that tests the new functions.
To add test code to the project
// Game.cpp : Defines the entry point for the console application. // #include "Cardgame.h" #include using namespace std; void PlayGames() < Cardgame bridge(4); Cardgame blackjack(8); Cardgame solitaire(1); Cardgame poker(5); >int main()
Build and run your app project
Next, build the project and run the app.
To build and run the project
- On the menu bar, choose Build >Build Solution. Output from a build is displayed in the Output window. If your build is successful, the output should resemble:
1>------ Build started: Project: Game, Configuration: Debug Win32 ------ 1>pch.cpp 1>Cardgame.cpp 1>Game.cpp 1>Generating Code. 1>Game.vcxproj -> C:\Users\\source\repos\Game\Debug\Game.exe ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
4 players have started a new game. There are now 4 players in total. 8 players have started a new game. There are now 12 players in total. 1 players have started a new game. There are now 13 players in total. 5 players have started a new game. There are now 18 players in total.
Congratulations, you've successfully built an app project and solution. Continue the walkthrough to learn more about how to build C++ code projects in Visual Studio.
Пошаговое руководство: Создание стандартной программы C++ (C++)
Вы можете использовать Visual Studio для создания программ C++ уровня "Стандартный". Выполнив действия, описанные в этом пошаговом руководстве, вы можете создать проект, добавить новый файл в проект, изменить файл, чтобы добавить код C++, а затем скомпилировать и запустить программу с помощью Visual Studio.
Вы можете ввести собственную программу C++ или использовать один из примеров программ. Пример программы в этом пошаговом руководстве является консольным приложением. Это приложение использует set контейнер в стандартной библиотеке C++.
Если требуется соответствие определенной версии стандарта языка C++ (например, C++14, C++17 или C++20), используйте параметр компилятора /std:c++14 , /std:c++17 или /std:c++20 . (Visual Studio 2017 и более поздние версии.)
Предварительные требования
Для выполнения этого пошагового руководства читатель должен владеть основами языка C++.
Создание проекта и добавление исходного файла
Приведенные ниже инструкции немного отличаются в зависимости от используемой версии Visual Studio. Чтобы ознакомиться с документацией по предпочтительной версии Visual Studio, используйте селектор Версия. Он находится в верхней части оглавления на этой странице.
Создание проекта C++ в Visual Studio
- В главном меню выберите Файл >Создать >Проект, чтобы открыть диалоговое окно Создание проекта.
- В верхней части диалогового окна задайте для параметра Язык значение C++, для параметра Платформа значение Windows, а для Типа проекта — Консоль.
- В отфильтрованном списке типов проектов щелкните Консольное приложение, а затем нажмите кнопку Далее. На следующей странице введите имя проекта и при необходимости укажите расположение проекта.
- Нажмите кнопку Создать, чтобы создать проект.
Создание проекта C++ в Visual Studio 2017
- Создайте проект, наведите указатель на пункт Создать в меню Файл и выберите Пункт Проект.
- В области Типы проектов Visual C++ щелкните Рабочий стол Windows, а затем — Консольное приложение Windows.
- Введите имя проекта. По умолчанию решение, содержащее проект, имеет то же имя, что и проект, но вы можете ввести другое имя. Вы также можете ввести другое расположение для проекта.
- Чтобы создать проект, нажмите кнопку ОК .
Создание проекта C++ в Visual Studio 2015
- Создайте проект, наведите указатель на пункт Создать в меню Файл и выберите Пункт Проект.
- В области Типы проектов Visual C++ щелкните Рабочий стол Windows, а затем — Консольное приложение Windows.
- В диалоговом окне Новый проект разверните узел Установленные>шаблоны>Visual C++, а затем выберите Win32. В центральной области выберите Консольное приложение Win32.
- Введите имя проекта. По умолчанию решение, содержащее проект, имеет то же имя, что и проект, но вы можете ввести другое имя. Вы также можете ввести другое расположение для проекта.
- Чтобы создать проект, нажмите кнопку ОК .
- Завершите работу мастера приложений Win32.
- Нажмите кнопку Далее, а затем убедитесь, что консольное приложение выбрано, и снимите флажок Предкомпилированные заголовки .
- Нажмите кнопку Готово.
Добавление нового исходного файла
- Если Обозреватель решений не отображается, в меню Вид выберите Обозреватель решений.
- Добавьте в проект новый исходный файл, как показано ниже.
- В Обозреватель решений щелкните правой кнопкой мыши папку Исходные файлы, наведите указатель на пункт Добавить и выберите пункт Создать элемент.
- В узле Код щелкните Файл C++ (CPP), введите имя файла и нажмите кнопку Добавить.
CPP-файл отображается в папке Исходные файлыв Обозреватель решений, а файл открывается в редакторе Visual Studio.