Compartilhar via


Walkthrough: Compiling a Native C++ Program on the Command Line

Visual C++ includes a C++ compiler that you can use to create everything from basic console apps to Windows Store applications and .NET components.

In this walkthrough, you create a basic Visual C++ console program by using a text editor, and then compile it on the command line.

Note

You can also use the Visual Studio integrated development environment (IDE) to compile Visual C++ programs. For more information, see Walkthrough: Working with Projects and Solutions (C++).

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

Prerequisites

To complete this walkthrough, you must understand the fundamentals of the C++ language.

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

  1. Open a Developer Command Prompt window. (On the Start window, open Apps. Open the Visual Studio Tools folder under your version of Visual Studio, and then choose the Developer Command Prompt shortcut.) For more information about how to open a Command Prompt window to use the command-line tools, see Setting the Path and Environment Variables for Command-Line Builds.

    Administrator credentials may be required to successfully compile the code in this walkthrough, depending on the computer's operating system and configuration. To run the Command Prompt window as an administrator, open the shortcut menu for Developer Command Prompt and then choose Run as administrator.

  2. At the command prompt, enter notepad basic.cpp.

    Choose Yes when you are prompted to create a file.

  3. In Notepad, enter these lines.

    #include <iostream>
    
    int main()
    {
        std::cout << "This is a native C++ program." << std::endl;
        return 0;
    }
    
  4. On the File menu, choose Save.

    You have created a Visual C++ source file.

  5. At the command prompt, enter cl /EHsc basic.cpp. (The /EHsc command-line option instructs the compiler to enable C++ exception handling. For more information, see /EH (Exception Handling Model).)

    The cl.exe compiler generates an .obj file that contains the compiled code, and then runs the linker to create an executable program named basic.exe. (This name appears in the lines of output information that the compiler displays.)

  6. To run the basic.exe program, at the command prompt, enter basic.

    The program displays this text and exits:

    This is a native C++ program.

See Also

Tasks

Visual C++ Guided Tour

Reference

Compiler Options

Other Resources

C++ Language Reference

Building C/C++ Programs