Последнее обновление: 30.01.2023
Установка компилятора
Рассмотрим создание первой простейшей программы на C++ с помощью компилятора g++, который на сегодняшний день является одним из
наиболее популярных компиляторов для C++, доступен для разных платформ и который распространяется в рамках пакета компиляторов GCC. Более подробную информацию о g++ можно получить на официальном сайте проекта https://gcc.gnu.org/.
Набор компиляторов GCC распространяется в различных версиях. Для Windows одной из наиболее популярных версий является пакет средств для разработки от
некоммерческого проекта MSYS2. Следует отметить, что для MSYS2 требуется 64-битная версия Windows 7 и выше (то есть Vista, XP и более ранние версии не подходят)
Итак, загрузим программу установки MSYS2 с официального сайта MSYS2:
После загрузки запустим программу установки:
На первом шаге установки будет предложено установить каталог для установки. По умолчанию это каталог C:\msys64:
Оставим каталог установки по умолчанию (при желании можно изменить). На следующем шаге устанавливаются настройки для ярлыка для меню Пуск, и затем собственно будет произведена установка.
После завершения установки нам отобразить финальное окно, в котором нажмем на кнопку Завершить
После завершения установки запустится консольное приложение MSYS2.exe. Если по каким-то причинам оно не запустилось,
то в папке установки C:/msys64 надо найти файл usrt_64.exe:
Теперь нам надо установить собственно набор компиляторов GCC. Для этого введем в этом приложении следующую команду:
pacman -S mingw-w64-ucrt-x86_64-gcc
Для управления пакетами MSYS2 использует пакетный менеджер Packman. И данная команда говорит пакетному менеджеру packman установить пакет mingw-w64-ucrt-x86_64-gcc,
который представляет набор компиляторов GCC (название устанавливаемого пакета указывается после параметра -S).
и после завершения установки мы можем приступать к программированию на языке C++. Если мы откроем каталог установки и зайдем в нем в папку C:\msys64\ucrt64\bin,
то найдем там все необходимые файлы компиляторов:
В частности, файл g++.exe как раз и будет представлять компилятор для языка С++.
Далее для упрощения запуска компилятора мы можем добавить путь к нему в Переменные среды. Для этого можно в окне поиска в Windows ввести «изменение переменных среды текущего пользователя»:
Нам откроется окно Переменных среды:
И добавим путь к компилятору C:\msys64\ucrt64\bin:
Чтобы убедиться, что набор компиляторов GCC успешно установлен, введем следующую команду:
В этом случае нам должна отобразиться версия компиляторов
Создание первой программы
Итак, компилятор установлен, и теперь мы можем написать первую программу. Для этого потребуется любой текстовый редактор для набора исходного кода.
Можно взять распространенный редактор Visual Studio Code или даже обычный встроенный Блокнот.
Итак, создадим на жестком диске С папку для исходных файлов. А в этой папке создадим новый текстовый файл, который переименуем в
hello.cpp. То есть по сути файлы исходного кода на С++ — это обычные текстовые файлы, которые, как правило, имеют расширение
cpp.
В моем случае файл hello.cpp находится в папке C:\cpp.
Теперь определим в файле hello.cpp простейший код, который будет выводить строку на консоль:
#include <iostream> // подключаем заголовочный файл iostream
int main() // определяем функцию main
{ // начало функции
std::cout << "Hello METANIT.COM!"; // выводим строку на консоль
return 0; // выходим из функции
} // конец функции
Для вывода строки на консоль необходимо подключить нужный функционал. Для этого в начале файла идет строка
#include <iostream>
Данная строка представляет директиву препроцессора, которая позволяет подключить библиотеку iostream. Эта библиотека нужна для вывода строки на консоль.
Далее идет определение функции main. Функция main должна присутствовать в любой программе на С++, с нее
собственно и начинается выполнение приложения.
Функция main состоит из четырех элементов:
-
Тип возвращаемого значения. В данном случае это тип int. Этот тип указывает, что функция должна
возвращать целое число. -
Имя функции. В данном случае функция называется main.
-
Список параметров. После имени функции в скобках идет список параметров. Но в данном случае скобки пустые, то есть
функция main не принимает параметров. -
Тело функции. После списка параметров в фигурных скобках идет тело функции. Здесь и определяются собственно те
действия, которые выполняет функция main.{ std::cout << "Hello METANIT.COM!"; return 0; }
В теле функции происходит вывод строки на консоль. Для обращения к консоли используется стандартный поток вывода std::cout.
С помощью оператора << в этот поток (в данном случае фактически на консоль) передается строка символов, которую надо вывести на консоль, то есть «Hello METANIT.COM!».
В конце осуществляем выход из функции с помощью оператора return. Так как функция должна возвращать целое число, то после return указывается число 0.
Ноль используется в качестве индикатора успешного завершения программы.
После каждой инструкции в языке C++ ставятся точка с запятой.
Каждая строка снабжена комментарием. Все, что написано после двойного слеша // представляет комментарий. Комментарий не учитывается при компиляции приложения, и
не является частью программного кода, а служат лишь для его описания. Комментарий позволяет понять, что делает программа.
Теперь скомпилируем этот файл. Для этого откроем командную строку Windows и вначале с помощью команды cd перейдем к папке с исходным файлом:
cd C:\cpp
Чтобы скомпилировать исходный код, необходимо компилятору gcc передать в качестве параметра файл hello.cpp:
g++ hello.cpp -o hello
Дополнительный необязательный параметр -o hello указывает, что скомпилированный файл будет называться hello.exe. Если не указать этот параметр, то файл будет называться по умолчанию — a.exe.
После выполнения этой команды будет скомпилирован исполняемый файл, который в Windows по умолчанию называется hello.exe. И мы можем обратиться к этому файлу, и в этом случае консоль выведет
строку «Hello METANIT.COM!», собственно как и прописано в коде.
Если вместо командной строки используется оболочка PowerShell, то для запуска файла надо прописать «./hello».
Стоит отметить, что мы можем совместить компиляцию и выполнение следующей командой:
g++ hello.cpp -o hello.exe & hello.exe
To run C++ code in Visual Studio, create a new project, write your C++ code in the editor, and then use the «Local Windows Debugger» option or press `F5` to compile and execute the program.
Here’s a simple C++ code snippet you can use as an example:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Getting Started with Visual Studio
What is Visual Studio?
Visual Studio is a comprehensive Integrated Development Environment (IDE) developed by Microsoft. It provides a powerful platform for coding, debugging, and managing C++ projects efficiently. With features such as IntelliSense, a powerful debugger, and support for various programming languages, it becomes an invaluable tool for both novice and experienced developers.
Installing Visual Studio
To start using Visual Studio for C++ development, you must first install it on your machine. Here’s how:
-
Download Visual Studio:
- Visit the [official Visual Studio website](https://visualstudio.microsoft.com/).
- Choose the version that suits your needs (the Community version is free for individual developers, open-source projects, and small teams).
-
Installation Steps:
- Open the installer and follow the prompts.
- When prompted to select workloads, choose Desktop Development with C++. This installs all necessary tools for C++ development, including compilers and standard libraries.
- Complete the installation process.
Setting Up Your Development Environment
Proper configuration is crucial for a smooth development experience. Here’s how to set up your environment:
- Ensure that the selected workload includes key components like the C++ compiler, standard libraries, and debugging tools.
- Familiarize yourself with the IDE layout, including the Solution Explorer, Output Window, and Properties Window.
How to Run a C++ Code in Visual Studio Easily
Creating a New C++ Project
Starting a New Project
To start programming in C++, you need to create a new project within Visual Studio:
- Open Visual Studio and click on `Create a new project`.
- In the project template selection window, filter by C++ and select the Console App template. Console apps are great for beginners as they are straightforward to implement.
- Name your project and select a suitable location on your machine. Click `Create`.
Understanding the Project Structure
Once you’ve created your project, take a moment to explore the Project Structure.
- main.cpp: This is the primary file where you will write your C++ code.
- Solution Explorer: This panel helps in managing all project files, allowing you to navigate easily between scripts and assets.
- Understanding this structure is key to organized coding and efficient project management.
How to Run C++ in Visual Studio: A Quick Guide
Writing Your First C++ Program
Basic C++ Syntax
Now that your project is set up, it’s time to write your first C++ program!
Here’s a simple program that outputs «Hello, World!» to the console:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
- Explanation of the Code:
- `#include <iostream>`: This line includes the Input/Output stream library, allowing you to use the `cout` function.
- `using namespace std;`: This line allows you to use standard library features without prefixing them with `std::`.
- `int main()`: This is the starting point of every C++ program.
- The `cout` statement outputs the text to the console, and `endl` flushes the output buffer, adding a new line.
How to Run C++ File in Visual Studio: A Quick Guide
Building and Running Your Code
Building Your Project
Once you’ve written your code, you need to build the project to compile it. Here’s how:
- Click on Build in the menu, then select Build Solution or simply press `Ctrl + Shift + B`.
- The Output Window will show you messages about the build status. A successful build will display “Build succeeded.”
Running Your Project
With the project built, it’s time to run it:
- Click on the green play button labeled Start Debugging or press `F5`. This runs the project in Debug mode (helpful for troubleshooting).
- If everything is set up correctly, you’ll see «Hello, World!» displayed in the console.
Using the Output Window
The Output Window provides essential feedback on your program’s execution. It will display any runtime errors or output from your program, enabling you to debug effectively.
How to Run C++ Program in Visual Studio: A Quick Guide
Debugging Your C++ Code
What is Debugging?
Debugging is a critical skill in programming. It involves identifying and fixing errors within your code. Understanding how to debug can vastly improve your development process and software quality.
Setting Breakpoints
In Visual Studio, you can set breakpoints to pause execution at a specific line of code, allowing you to inspect variable values and program flow.
- To set a breakpoint, click on the left margin next to the line number in your code. A red dot will appear, indicating a breakpoint.
- Run your project in Debug mode, and it will pause when it reaches this line.
Inspecting Variables and Call Stack
While debugging, you can check the values of variables:
- Hover over a variable to see its current value.
- Use the Locals window to view all variables in the current scope.
To understand how your program reached its current state, explore the Call Stack. This window shows the active function calls, providing insight into the execution flow.
How to Use C++ in Visual Studio: A Handy Guide
Tips for Successful C++ Development in Visual Studio
Utilizing Visual Studio Features
Make the most of Visual Studio’s features:
- IntelliSense: This feature provides suggestions and autocompletes code, speeding up the coding process and reducing errors.
- Code Snippets: Learn to use predefined snippets to simplify writing common constructs.
Learning Resources
Seek out additional materials to enhance your skills:
- Explore official C++ documentation for comprehensive language features.
- Look for reputable online tutorials and courses tailored for beginners.
How to Use C++ on Visual Studio: A Quick Guide
Troubleshooting Common Issues
Common Errors and Fixes
As you work with Visual Studio, you may encounter errors. Here are a few common ones:
- Compilation Errors: These usually occur due to syntax errors. Read the error messages in the Output Window for guidance on what’s wrong.
- Linker Errors: Ensure all libraries and dependencies are correctly included in your project settings.
Finding Help
When you face challenges, don’t hesitate to seek help. Utilize platforms such as Stack Overflow, and engage with the C++ community through forums or local user groups.
How to Get C++ on Visual Studio: A Quick Start Guide
Conclusion
Running C++ code in Visual Studio is a structured process that unfolds in steps: from installing the IDE, creating a project, writing your code, to building and debugging it. By following this guide, you should now have the tools and knowledge to begin your journey in C++ programming efficiently.
Additional Resources
To further your learning, explore the official C++ documentation and consider diving into foundational books that cover advanced topics in C++ programming. Remember, the best way to learn is through practice!
Post Views: 1,237
In this tutorial, We are going to learn about how to run a C++ file in Command Prompt or CMD. So let’s know a little what is CMD.
Running C ++ programs using the command prompt is useful if you do not have an IDE installed on your computer. It uses simple steps to run C++ programs.
Steps to launch the C ++ program in CMD
- Right-click and navigate to the Computer icon and then to the Properties option.
2. Then go to system settings and go to variable environment.
3. A new window will appear and then click a new button. In the variable word field, you need to enter the path and folder of a different value bin.
4.You will find the path to the bin folder by clicking directly on the directory where you are having your compiler.
5. After all the above steps click on OK button to save all the information.
6. Then press the key Win+R to open Run. There you need to type cmd and then press enter key to open the cmd prompt. Now you have to change the directory where you have saved the required C++ program files.
8. You can start compiling the program type gcc filename. Click the enter button without .cpp or.c extension in order to run the program.
9. Output will be seen on the screen.
Visual Studio Code (or VS Code for short) is a very common and widely used text editor and IDE (Integrated Development Environment). You can make VS Code very powerful like an IDE using a lot of extensions.
Before approaching the process of running your first C or C++ code on Visual Studio Code, let me guide you through the process and get it all set up based on the operating system you are using on your computer.
C and C++ compilers
For running C or C++ code, you just need to have a valid C/C++ compiler installed on your computer. If you are using a Linux operating system, then there is a high chance that it is already installed on your system. But we need to make sure that it is correctly installed.
For checking whether or not you have the compiler (GCC/G++/MinGW) installed on your system or not, you have to check the compiler version first.
Simply open your terminal and use gcc --version and g++ --version. If you get the version number, then the compiler is already installed on your system.
You can check the version using the same commands on any operating system, whether that is a Windows, Linux, or macOS-based operating system.
If you get feedback on your terminal that it does not know anything about GCC or G++, then you have to install the compiler correctly.
If you are using the most used Windows operating system, then I already have written an in-depth article showing you all the processes step-by-step on freeCodeCamp. Make sure to read the entire article first, as it also contains a complete video to provide you with complete support.
Embedded content
If you are using another operating system, and you don’t have the compilers installed, then make sure to install them before proceeding.
How to Install VS Code or VS Code Insiders
You have to download Visual Studio Code directly from the official website: https://code.visualstudio.com/.
If you want, you can also install VS Code Insiders, and the same process is applicable for that as well.
Visual Studio Code Insiders is actually the «Insiders» build of Visual Studio Code, which contains all the latest features that are shipped daily. You can think of VS Code as the stable release and the VS Code Insiders as the Insiders release of that.
If you want to experience the latest updates instantly, then you might also try Visual Studio Code Insiders (I use it myself). For downloading VS Code Insiders, you can visit the official website for VS Code Insiders here: https://code.visualstudio.com/insiders/
Make sure to download the exact file for your operating system.
Download Page: VS Code
Download Page: VS Code Insiders
The installation process is pretty basic. But I am going to show you all the steps sequentially. For now, I am going to show you the installation process using VS Code Insiders, but everything you will see here is going to be exactly the same for VS Code as well.
Make sure to click the box on the «I accept the agreement » box and click on Next.
Accept the agreement and click Next
Keep everything as it is. Do not change anything from here.
Click Next
Click Next. Again, simply click Next.
Click Next
Make sure to add the checkmark (✔) on all of the boxes. Then click on Next.
Check all of the boxes, and click Next
Click on Install.
Click Install
It might take a little time to finish the installation.
Let it finish…
Click on Finish.
Click Finish
Congrats — you’ve successfully installed VS Code/VS Code Insiders on your system. Now, cheers! 🥂
How to Prepare VS Code/VS Code Insiders For C and C++ Code
First, open VS Code or VS Code Insiders.
Go to the Extension tab. Search for «C» or «C++» and install the first one that is already verified by Microsoft itself.
Install C/C++ extension
Also, install C/C++ Extension Pack. It should also be verified by Microsoft.
Install C/C++ Extension Pack
Then you have to search for Code Runner and install the extension as well.
Install Code Runner Extension
Now, we need to change some settings.
Change some settings
Click the gear box (It is called the Manage section), and then click Settings. Alternatively, you can also use the shortcut keys Ctrl + ,. You need to replace the Ctrl key with the Command key for Mac.
Type «Run code in terminal» and press Enter key
In the search bar, type «Run code in terminal» and press the Enter key.
Scroll down a little bit until you find Code-runner: Run In Terminal. Make sure that the box is checked (✔).
Make sure to check the box
Now you need to restart your VS Code/VS Code Insiders. Simply close and reopen the program.
How to Test Your Code
Simply open VS Code/VS Code Insiders, open any folder, and create any file with the extension .c for the C file and .cpp for the C++ file.
After writing your code, you can run the code directly using the play button you’ll find in the upper right corner.
This is how you can run any C/C++ program from VS Code/Insiders
It will compile and then run the code directly. After running a code, the code runner button would be set default to run directly. So, your computer is 100% ready for compiling and running any C/C++ programming code. 😀
Conclusion
Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at freeCodeCamp.
If you want to get in touch with me, then you can do so using Twitter, LinkedIn, and GitHub.
You can also SUBSCRIBE to my YouTube channel (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.
If you want to check out my highlights, then you can do so at my Polywork timeline.
You can also visit my website to learn more about me and what I’m working on.
Thanks a bunch!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Download Article
Turn your C files into programs you can run
Download Article
- Installing Visual Studio
- Writing the Program
- Compiling and Running
|
|
If you’ve written or downloaded some C code on your Windows PC, you’ll need to compile the code to turn it into a program you can run. You can easily do so using the developer command prompt for Visual Studio, which is free to download for personal use. The developer command prompt works just like the standard command prompt, but has extra developer commands, such as the ability to compile and run C programs. This wikiHow article teaches you how to compile and run C programs using the developer command line.
Quick Steps
- Download and install Visual Studio Desktop Development with C++
- Write your C program using a text program such as Notepad.
- Save the file as a “.c” file.
- Open the Developer Command Prompt as an administrator.
- Type “cl” followed by the filename of your C program and press Enter.
- Type the executable name and press Enter to run the program.
-
Go to https://visualstudio.microsoft.com/downloads in a web browser. Visual Studio not only contains an IDE that allows you to write and compile C programs, but it also contains a Developer Command Prompt that allows you to compile C programs. The Developer Command Prompt works just like the regular Windows Command Prompt, except it has environment variables that allow you to run commands to compile C programs.
-
If you are just learning how to write a program or using it for personal use, click Free Download below “Community.” This is the free version of Visual Studio. If you are working for a small team, you can click Free Trial below “Professional.” If you work for a large company, you can click Free Trial below “Enterprise.” This will download the Visual Studio installer.
Advertisement
-
You can find it in your downloads folder by default. This will launch the Visual Studio installer. Once the installer launches, it will inform you that you need to set up a few things to configure the installation. Click Continue to proceed.
-
Installing Desktop Development with C++ will install the components needed to write and compile C++ and C programs. You can also install any other languages you are interested in working on (i.e., Python development).[1]
- Depending on what you are interested in working on, you may want to install other C++ development workloads, such as Mobile development with C++, Game development with C++, or WinUI application development.
- Additionally, you can click the Individual Components tab at the top and check individual boxes next to the tools you want to install, such as C++/CLI support.
-
This will begin installing the development workloads you selected. This may take a while.
Advertisement
-
You can use a basic text program such as Notepad to write basic C programs. Notepad comes pre-installed on Windows. You can find Notepad in the Windows Start menu.
- Alternatively, you can use a program such as Notepad++ or an integrated development environment such as Eclipse to write C programs. These programs have tools to assist you with writing code.
-
You can write your entire C program in Notepad. If you have no programming experience, you may want to take some time to learn. You can find plenty of tutorials online with examples of basic C programs.[2]
-
Use the following steps to do so:
- Click File in the menu bar at the top.
- Click Save as in the drop-down menu.
- Select All files next to “Save as type.”
- Enter a filename for the file.
- Add the extension “.c” at the end of the filename.
- Click Save.
Advertisement
-
Visual Studio installs a Developer Command Prompt that works just like CMD, but allows you to execute developer commands. Use the following steps to open the Developer Command Prompt.
- Click the Windows Start button.
- Type developer command prompt
- Right-click Developer Command Prompt for VS.
- Click Run as administrator.
-
You can change directories using the “CD” command. Type cd followed by the path to the location of your C program and press Enter. For example; cd C:\Users\[username]\Documents\C Programs\Hello.
-
For example, cl hello.c. This will compile the program and output an executable (.exe) file.
- You can compile more than one file at a time. To do so, enter each filename after the “cl” command separated by a space. For example, cl file1.c file2.c file3.c
- If you want to change the name of the executable file, type /out: followed by the name you want to give the executable file at the end of the command. For example, cl hello.c /out:helloworld.exe
-
To run the executable file in the command line, simply type the filename of the executable file (i.e., “helloworld.exe”) and press Enter. This will run the executable file.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 326,773 times.
