Hello World C++ Visual Studio Code

  



Launching Visual Studio. View code Rich Interactive. This basic example creates a box titled 'Hello, World!' And displays it in your terminal.

-->
  • Using GCC with MinGW. In this tutorial, you configure Visual Studio Code to use the GCC C compiler (g) and GDB debugger from mingw-w64 to create programs that run on Windows. After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you about GCC, GDB, Mingw-w64, or the C language.
  • Free downloads for building and running.NET apps on Linux, macOS, and Windows. Runtimes, SDKs, and developer packs for.NET Framework,.NET Core, and ASP.NET.
  • In this walkthrough, you create a basic, 'Hello, World'-style C program by using a text editor, and then compile it on the command line. If you'd like to try the Visual Studio IDE instead of using the command line, see Walkthrough: Working with Projects and Solutions (C) or Using the Visual Studio IDE for C Desktop Development.

This topic walks you through creating a Windows 10 Universal Windows Platform (UWP) 'Hello, World!' app using C++/WinRT. The app's user interface (UI) is defined using Extensible Application Markup Language (XAML).

C++

C++/WinRT is an entirely standard modern C++17 language projection for Windows Runtime (WinRT) APIs. For more info, and more walkthroughs and code examples, see the C++/WinRT documentation. A good topic to begin with is Get started with C++/WinRT.

Set up Visual Studio for C++/WinRT

For info about setting up Visual Studio for C++/WinRT development—including installing and using the C++/WinRT Visual Studio Extension (VSIX) and the NuGet package (which together provide project template and build support)—see Visual Studio support for C++/WinRT.

To download Visual Studio, see Downloads.

For an introduction to XAML, see XAML overview

Create a Blank App (HelloWorldCppWinRT)

Our first app is a 'Hello, World!' app that demonstrates some basic features of interactivity, layout, and styles.

Begin by creating a new project in Microsoft Visual Studio. Create a Blank App (C++/WinRT) project, and name it HelloWorldCppWinRT. Make sure that Place solution and project in the same directory is unchecked. Target the latest generally-available (that is, not preview) version of the Windows SDK.

In a later section of this topic, you'll be directed to build your project (but don't build until then).

About the project files

Typically, in the project folder, each .xaml (XAML markup) file has a corresponding .idl, .h, and .cpp file. Together, those files compile into a XAML page type.

You can modify a XAML markup file to create UI elements, and you can bind those elements to data sources (a task known as data binding). You modify the .h, and .cpp files (and sometimes the .idl file) to add custom logic for your XAML page—event handlers, for example.

Let's look at some of the project files.

  • App.idl, App.xaml, App.h, and App.cpp. These files represent your app's specialization of the Windows::UI::Xaml::Application class, which includes your app's entry point. App.xaml doesn't contain any page-specific markup, but you can add user interface element styles there, as well as any other elements that you want to be accessible from all pages. The .h and .cpp files contain handlers for various application lifecycle events. Typically, you add custom code there to initialize your app when it starts, and to perform cleanup when it's either suspended or terminated.
  • MainPage.idl, MainPage.xaml, MainPage.h, and MainPage.cpp. Contain the XAML markup, and implementation, for the default main (startup) page type in an app, which is the MainPage runtime class. MainPage has no navigation support, but it provides some default UI, and an event handler, to get you started.
  • pch.h and pch.cpp. These files represent your project's precompiled header file. In pch.h, include any header files that don't change often, and then include pch.h in other files in the project.

A first look at the code

How To Use Visual Studio Code

Runtime classes

As you may know, all of the classes in a Universal Windows Platform (UWP) app written in C# are Windows Runtime types. But when you author a type in a C++/WinRT application, you can choose whether that type is a Windows Runtime type, or a regular C++ class/struct/enumeration.

Any XAML page type in your project needs to be a Windows Runtime type. So MainPage is a Windows Runtime type. Specifically, it's a runtime class. Any type that's consumed by a XAML page also needs to be a Windows Runtime type. When you're writing a Windows Runtime component, and you want to author a type that can be consumed from another app, then you'll author a Windows Runtime type. In other cases, your type can be a regular C++ type. Generally speaking, a Windows Runtime type can be consumed using any Windows Runtime language.

One good indication that a type is a Windows Runtime type is that it's defined in Microsoft Interface Definition Language (MIDL) inside an Interface Definition Language (.idl) file. Let's take MainPage as an example.

And here's the basic structure of the implementation of the MainPage runtime class, and its activation factory, as seen in MainPage.h.

For more details about whether or not you should author a runtime class for a given type, see the topic Author APIs with C++/WinRT. And for more info about the connection between runtime classes and IDL (.idl files), you can read and follow along with the topic XAML controls; bind to a C++/WinRT property. That topic walks through the process of authoring a new runtime class, the first step of which is to add a new Midl File (.idl) item to the project.

Now let's add some functionality to the HelloWorldCppWinRT project.

Step 1. Modify your startup page

In Solution Explorer, open MainPage.xaml so that you can author the controls that form the user interface (UI).

Delete the StackPanel that's in there already, as well as its contents. In its place, paste the following XAML.

C++

This new StackPanel has a TextBlock that prompts for the user's name, a TextBox that accepts the user's name, a Button, and another TextBlock element.

Since we deleted the Button named myButton, we'll have to remove the reference to it from the code. So, in MainPage.cpp, delete the line of code inside the MainPage::ClickHandler function.

At this point, you've created a very basic Universal Windows app. To see what the UWP app looks like, build and run the app.

In the app, you can type into the text box. But clicking the button doesn't do anything yet.

Step 2. Add an event handler

In MainPage.xaml, find the Button named inputButton, and declare an event handler for its ButtonBase::Click event. The markup for the Button should now look like this.

Implement the event handler like this.

For more info, see Handle events by using delegates.

The implementation retrieves the user's name from the text box, uses it to create a greeting, and displays that in the greetingOutput text block.

Build and run the app. Type your name in the text box, and click the button. The app displays a personalized greeting.

Step 3. Style the startup page

Choose a theme

It's easy to customize the look and feel of your app. By default, your app uses resources that have a light-colored style. The system resources also include a dark theme.

To try out the dark theme, edit App.xaml, and add a value for Application::RequestedTheme.

For apps that display mostly images or video, we recommend the dark theme; for apps that contain a lot of text, we recommend the light theme. If you're using a custom color scheme, then use the theme that goes best with your app's look and feel.

Note

A theme is applied when your app starts up. It can't be changed while the app is running.

Use system styles

In this section we'll change the appearance of the text (for example, make the font size larger).

World

In MainPage.xaml, find the 'What's your name?' TextBlock. Set its Style property to a reference to the BaseTextBlockStyle system resource key.

BaseTextBlockStyle is the key of a resource that's defined in the ResourceDictionary in Program Files (x86)Windows Kits10DesignTimeCommonConfigurationNeutralUAP<version>Genericgeneric.xaml. Here are the property values that are set by that style.

Also in MainPage.xaml, find the TextBlock named greetingOutput. Set its Style to BaseTextBlockStyle also. If you build and run the app now, you'll see that the appearance of both text blocks has changed (for example, the font size is now larger).

Step 4. Have the UI adapt to different window sizes

Now we'll cause the UI to adapt dynamically to a changing window size, and so that it looks good on devices with small displays. To do this, you'll add a VisualStateManager section into MainPage.xaml. You'll define different visual states for different window sizes, and then set the properties to apply for each of those visual states.

Adjust the UI layout

Add this block of XAML as the first child element of the root StackPanel element.

Build and run the app. Notice that the UI looks the same as before until the window is resized narrower than 641 device-independent pixels (DIPs). At that point, the narrowState visual state is applied and, along with it, all of the property setters defined for that state.

The VisualState named wideState has an AdaptiveTrigger with its MinWindowWidth property set to 641. This means that the state is to be applied only when the window width is not less than the minimum of 641 DIPs. You don't define any Setter objects for this state, so it uses the layout properties that you defined in the XAML for the page content.

The second VisualState, narrowState, has an AdaptiveTrigger with its MinWindowWidth property set to 0. This state is applied when the window width is greater than 0, but less than 641 DIPs. At exactly 641 DIPs, wideState is in effect. In narrowState, you define Setter objects to change the layout properties of controls in the UI.

  • You reduce the left margin of the contentPanel element from 120 to 20.
  • You change the Orientation of the inputPanel element from Horizontal to Vertical.
  • You add a top margin of 4 DIPs to the inputButton element.

Summary

This walkthrough showed you how to add content to a Windows Universal app, how to add interactivity, and how to change the UI's appearance.

-->

Visual Studio includes a command-line C and C++ compiler. You can use it to create everything from basic console apps to Universal Windows Platform apps, Desktop apps, device drivers, and .NET components.

In this walkthrough, you create a basic, 'Hello, World'-style C++ program by using a text editor, and then compile it on the command line. If you'd like to try the Visual Studio IDE instead of using the command line, see Walkthrough: Working with Projects and Solutions (C++) or Using the Visual Studio IDE for C++ Desktop Development.

In this walkthrough, you can use your own C++ program instead of typing the one that's shown. Or, you can use a C++ code sample from another help article.

Vscode C++ Hello World

Prerequisites

To complete this walkthrough, you must have installed either Visual Studio and the optional Desktop development with C++ workload, or the command-line Build Tools for Visual Studio.

Visual Studio is an integrated development environment (IDE). It supports a full-featured editor, resource managers, debuggers, and compilers for many languages and platforms. Versions available include the free Visual Studio Community edition, and all can support C and C++ development. For information on how to download and install Visual Studio, see Install C++ support in Visual Studio.

The Build Tools for Visual Studio installs only the command-line compilers, tools, and libraries you need to build C and C++ programs. It's perfect for build labs or classroom exercises and installs relatively quickly. To install only the command-line tools, look for Build Tools for Visual Studio on the Visual Studio Downloads page.

Before you can build a C or C++ program on the command line, verify that the tools are installed, and you can access them from the command line. Visual C++ has complex requirements for the command-line environment to find the tools, headers, and libraries it uses. You can't use Visual C++ in a plain command prompt window without doing some preparation. Fortunately, Visual C++ installs shortcuts for you to launch a developer command prompt that has the environment set up for command line builds. Unfortunately, the names of the developer command prompt shortcuts and where they're located are different in almost every version of Visual C++ and on different versions of Windows. Your first walkthrough task is finding the right one to use.

Note

A developer command prompt shortcut automatically sets the correct paths for the compiler and tools, and for any required headers and libraries. You must set these environment values yourself if you use a regular Command Prompt window. For more information, see Set the Path and Environment Variables for Command-Line Builds. We recommend you use a developer command prompt shortcut instead of building your own.

Open a developer command prompt

  1. If you have installed Visual Studio 2017 or later on Windows 10, open the Start menu and choose All apps. Scroll down and open the Visual Studio folder (not the Visual Studio application). Choose Developer Command Prompt for VS to open the command prompt window.

    If you have installed Microsoft Visual C++ Build Tools 2015 on Windows 10, open the Start menu and choose All apps. Scroll down and open the Visual C++ Build Tools folder. Choose Visual C++ 2015 x86 Native Tools Command Prompt to open the command prompt window.

    You can also use the Windows search function to search for 'developer command prompt' and choose one that matches your installed version of Visual Studio. Use the shortcut to open the command prompt window.

  2. Next, verify that the Visual C++ developer command prompt is set up correctly. In the command prompt window, enter cl and verify that the output looks something like this:

    There may be differences in the current directory or version numbers. These values depend on the version of Visual C++ and any updates installed. If the above output is similar to what you see, then you're ready to build C or C++ programs at the command line.

    Note

    If you get an error such as 'cl' is not recognized as an internal or external command, operable program or batch file,' error C1034, or error LNK1104 when you run the cl command, then either you are not using a developer command prompt, or something is wrong with your installation of Visual C++. You must fix this issue before you can continue.

    If you can't find the developer command prompt shortcut, or if you get an error message when you enter cl, then your Visual C++ installation may have a problem. Try reinstalling the Visual C++ component in Visual Studio, or reinstall the Microsoft Visual C++ Build Tools. Don't go on to the next section until the cl command works. For more information about installing and troubleshooting Visual C++, see Install Visual Studio.

    Note

    Depending on the version of Windows on the computer and the system security configuration, you might have to right-click to open the shortcut menu for the developer command prompt shortcut and then choose Run as administrator to successfully build and run the program that you create by following this walkthrough.

Create a Visual C++ source file and compile it on the command line

  1. In the developer command prompt window, enter md c:hello to create a directory, and then enter cd c:hello to change to that directory. This directory is where both your source file and the compiled program get created.

  2. Enter notepad hello.cpp in the command prompt window.

    Choose Yes when Notepad prompts you to create a new file. This step opens a blank Notepad window, ready for you to enter your code in a file named hello.cpp.

  3. In Notepad, enter the following lines of code:

    This code is a simple program that will write one line of text on the screen and then exit. To minimize errors, copy this code and paste it into Notepad.

  4. Save your work! In Notepad, on the File menu, choose Save.

    Congratulations, you've created a C++ source file, hello.cpp, that is ready to compile.

  5. Switch back to the developer command prompt window. Enter dir at the command prompt to list the contents of the c:hello directory. You should see the source file hello.cpp in the directory listing, which looks something like:

    The dates and other details will differ on your computer.

    Note

    If you don't see your source code file, hello.cpp, make sure the current working directory in your command prompt is the C:hello directory you created. Also make sure that this is the directory where you saved your source file. And make sure that you saved the source code with a .cpp file name extension, not a .txt extension. Your source file gets saved in the current directory as a .cpp file automatically if you open Notepad at the command prompt by using the notepad hello.cpp command. Notepad's behavior is different if you open it another way: By default, Notepad appends a .txt extension to new files when you save them. It also defaults to saving files in your Documents directory. To save your file with a .cpp extension in Notepad, choose File > Save As. In the Save As dialog, navigate to your C:hello folder in the directory tree view control. Then use the Save as type dropdown control to select All Files (*.*). Enter hello.cpp in the File name edit control, and then choose Save to save the file.

  6. At the developer command prompt, enter cl /EHsc hello.cpp to compile your program.

    The cl.exe compiler generates an .obj file that contains the compiled code, and then runs the linker to create an executable program named hello.exe. This name appears in the lines of output information that the compiler displays. The output of the compiler should look something like:

    Note

    If you get an error such as 'cl' is not recognized as an internal or external command, operable program or batch file,' error C1034, or error LNK1104, your developer command prompt is not set up correctly. For information on how to fix this issue, go back to the Open a developer command prompt section.

    Note

    If you get a different compiler or linker error or warning, review your source code to correct any errors, then save it and run the compiler again. For information about specific errors, use the search box to look for the error number.

  7. To run the hello.exe program, at the command prompt, enter hello.

    The program displays this text and exits:

    Congratulations, you've compiled and run a C++ program by using the command-line tools.

Next steps

This 'Hello, World' example is about as simple as a C++ program can get. Real world programs usually have header files, more source files, and link to libraries.

You can use the steps in this walkthrough to build your own C++ code instead of typing the sample code shown. These steps also let you build many C++ code sample programs that you find elsewhere. You can put your source code and build your apps in any writeable directory. By default, the Visual Studio IDE creates projects in your user folder, in a sourcerepos subfolder. Older versions may put projects in a *DocumentsVisual Studio <version>Projects folder.

To compile a program that has additional source code files, enter them all on the command line, like:

cl /EHsc file1.cpp file2.cpp file3.cpp

The /EHsc command-line option instructs the compiler to enable standard C++ exception handling behavior. Without it, thrown exceptions can result in undestroyed objects and resource leaks. For more information, see /EH (Exception Handling Model).

When you supply additional source files, the compiler uses the first input file to create the program name. In this case, it outputs a program called file1.exe. To change the name to program1.exe, add an /out linker option:

cl /EHsc file1.cpp file2.cpp file3.cpp /link /out:program1.exe

And to catch more programming mistakes automatically, we recommend you compile by using either the /W3 or /W4 warning level option:

cl /W4 /EHsc file1.cpp file2.cpp file3.cpp /link /out:program1.exe

The compiler, cl.exe, has many more options. You can apply them to build, optimize, debug, and analyze your code. For a quick list, enter cl /? at the developer command prompt. You can also compile and link separately and apply linker options in more complex build scenarios. For more information on compiler and linker options and usage, see C/C++ Building Reference.

You can use NMAKE and makefiles, MSBuild and project files, or CMake, to configure and build more complex projects on the command line. For more information on using these tools, see NMAKE Reference, MSBuild, and CMake projects in Visual Studio.

The C and C++ languages are similar, but not the same. The MSVC compiler uses a simple rule to determine which language to use when it compiles your code. By default, the MSVC compiler treats files that end in .c as C source code, and files that end in .cpp as C++ source code. To force the compiler to treat all files as C++ independent of file name extension, use the /TP compiler option.

The MSVC compiler includes a C Runtime Library (CRT) that conforms to the ISO C99 standard, with minor exceptions. Portable code generally compiles and runs as expected. Certain obsolete library functions, and several POSIX function names, are deprecated by the MSVC compiler. The functions are supported, but the preferred names have changed. For more information, see Security Features in the CRT and Compiler Warning (level 3) C4996.

See also

C++ Language Reference
Projects and build systems
MSVC Compiler Options