演练:在命令行上编译本机 C++ 程序Walkthrough: Compiling a Native C++ Program on the Command Line

Visual Studio 包含命令行 C 和 C++ 编译器。Visual Studio includes a command-line C and C++ compiler. 可以使用它创建从基本控制台应用到通用 Windows 平台应用、桌面应用、设备驱动程序和 .NET 组件的所有内容。You can use it to create everything from basic console apps to Universal Windows Platform apps, Desktop apps, device drivers, and .NET components.

在此演练中,你将使用文本编辑器创建一个基本的“Hello, World”程序,然后在命令行上对其进行编译。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. 如果想尝试使用 Visual Studio IDE 而不是使用命令行,请参阅演练:使用项目和解决方案 (C++)使用 Visual Studio IDE 进行 C++ 桌面开发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.

在本演练中,你可以使用自己的 C++ 程序而不是键入显示的程序。In this walkthrough, you can use your own C++ program instead of typing the one that's shown. 也可以使用另一个帮助文章中的 C++ 代码示例。Or, you can use a C++ code sample from another help article.

先决条件Prerequisites

要完成此演练,必须安装 Visual Studio 和可选的“使用 C++ 进行桌面开发”工作负载,或 Visual Studio 的命令行生成工具。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 是一个集成开发环境 (IDE)。Visual Studio is an integrated development environment (IDE). 它支持多种语言和平台的功能完备的编辑器、资源管理器、调试器和编译器。It supports a full-featured editor, resource managers, debuggers, and compilers for many languages and platforms. 可用版本包括免费的 Visual Studio Community 版本,且所有版本都支持 C 和 C++ 开发。Versions available include the free Visual Studio Community edition, and all can support C and C++ development. 有关如何下载和安装 Visual Studio 的信息,请参阅在 Visual Studio 中安装 C++ 支持For information on how to download and install Visual Studio, see Install C++ support in Visual Studio.

Visual Studio 生成工具只安装生成 C 和 C++ 程序所需的命令行编译器、工具和库。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. 如果只安装命令行工具,请在 Visual Studio 下载页面上查找 Visual Studio 生成工具。To install only the command-line tools, look for Build Tools for Visual Studio on the Visual Studio Downloads page.

在命令行上生成 C 或 C++ 程序之前,请验证是否安装了这些工具,并且是否可以从命令行访问它们。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++ 对用于查找其使用的工具、标头和库的命令行环境有复杂的要求。Visual C++ has complex requirements for the command-line environment to find the tools, headers, and libraries it uses. 如果没有事先准备,在普通的命令提示窗口中不能使用 Visual C++。You can't use Visual C++ in a plain command prompt window without doing some preparation. 幸运的是,Visual C++ 为你安装了快捷方式来启动开发人员命令提示,该命令提示符为命令行生成设置了环境。Fortunately, Visual C++ installs shortcuts for you to launch a developer command prompt that has the environment set up for command line builds. 遗憾的是,开发人员命令提示快捷方式的名称和它们所在的位置在几乎所有版本的 Visual C++ 和不同版本的 Windows 中都是不同的。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.

备注

开发人员命令提示快捷方式自动为编译器和工具以及所有必需的标头和库设置正确的路径。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. 如果在 Windows 10 上安装了 Visual Studio 2017 或更高版本,请打开“开始”菜单并选择“所有应用”。If you have installed Visual Studio 2017 or later on Windows 10, open the Start menu and choose All apps. 向下滚动并打开“Visual Studio”文件夹(不是 Visual Studio 应用程序)。Scroll down and open the Visual Studio folder (not the Visual Studio application). 选择“VS 开发人员命令提示”以打开命令提示窗口。Choose Developer Command Prompt for VS to open the command prompt window.

    如果在 Windows 10 上安装了 Microsoft Visual C++ 生成工具 2015,请打开“开始”菜单并选择“所有应用” 。If you have installed Microsoft Visual C++ Build Tools 2015 on Windows 10, open the Start menu and choose All apps. 向下滚动并打开“Visual C++ 生成工具”文件夹。Scroll down and open the Visual C++ Build Tools folder. 选择“Visual C++ 2015 x86 本机工具命令提示”,打开命令提示窗口。Choose Visual C++ 2015 x86 Native Tools Command Prompt to open the command prompt window.

    还可以使用 Windows 搜索功能搜索“开发人员命令提示”,然后选择与安装的 Visual Studio 版本匹配的命令提示。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. 接下来,验证 Visual C++ 开发人员命令提示是否设置正确。Next, verify that the Visual C++ developer command prompt is set up correctly. 在命令提示窗口中,输入 cl,并验证输出是否如下所示:In the command prompt window, enter cl and verify that the output looks something like this:

    C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise>cl
    Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25017 for x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    usage: cl [ option... ] filename... [ /link linkoption... ]
    

    当前目录或版本号可能存在差异。There may be differences in the current directory or version numbers. 这些值取决于 Visual C++ 的版本和安装的任何更新。These values depend on the version of Visual C++ and any updates installed. 如果上述输出与所看到的类似,则可以在命令行中生成 C 或 C++ 程序。If the above output is similar to what you see, then you're ready to build C or C++ programs at the command line.

    备注

    当你运行 cl 命令时,如果遇到错误,例如“CL 无法识别为内部或外部命令、可操作的程序或批处理文件”、错误 C1034 或错误 LNK1104,则说明你没有使用开发人员命令提示,或者安装 Visual C++ 时出现了错误。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.

    如果找不到开发人员命令提示快捷方式,或在输入 cl 时收到错误消息,则说明 Visual C++ 安装可能有问题。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. 尝试在 Visual Studio 中重新安装 Visual C++ 组件,或重新安装 Microsoft Visual C++ 生成工具。Try reinstalling the Visual C++ component in Visual Studio, or reinstall the Microsoft Visual C++ Build Tools. 除非 cl 命令运行,否则不要继续下一节。Don't go on to the next section until the cl command works. 有关 Visual C++ 的安装和故障排除的更多信息,请参阅安装 Visual StudioFor more information about installing and troubleshooting Visual C++, see Install Visual Studio.

    备注

    根据计算机上的 Windows 版本和系统安全配置,可能必须右键单击以打开“开发人员命令提示”快捷方式的快捷菜单,然后选择“以管理员身份运行”,才能成功生成和运行通过本演练创建的程序。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.

创建 Visual C++ 源文件并在命令行上对其进行编译Create a Visual C++ source file and compile it on the command line

  1. 在“开发人员命令提示”窗口中,输入 md c:\hello 以创建目录,然后输入 cd c:\hello 更改为该目录。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 your source file and the compiled program are created in.

  2. 在命令提示窗口中输入 notepad hello.cppEnter notepad hello.cpp in the command prompt window.

    当记事本提示你创建文件时,选择“是”。Choose Yes when Notepad prompts you to create a file. 此步骤将打开一个空白记事本窗口,你可以在名为 hello.cpp 的文件中输入代码。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:

    #include <iostream>
    using namespace std;
    int main()
    {
        cout << "Hello, world, from Visual C++!" << endl;
    }
    

    此代码是一个非常简单的程序,会在屏幕上写入一行文本,然后退出。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.

    恭喜,你已经创建了一个 C++ 源文件 Helo.cp,可以进行编译。Congratulations, you've created a C++ source file, hello.cpp, that is ready to compile.

  5. 切换回开发人员命令提示窗口。Switch back to the developer command prompt window. 在命令提示符下输入 dir 以列出 c:\hello 目录的内容。Enter dir at the command prompt to list the contents of the c:\hello directory. 目录列表中应显示源文件 hello.cpp,如下所示:You should see the source file hello.cpp in the directory listing, which looks something like:

    c:\hello>dir
     Volume in drive C has no label.
     Volume Serial Number is CC62-6545
    
     Directory of c:\hello
    
    05/24/2016  05:36 PM    <DIR>          .
    05/24/2016  05:36 PM    <DIR>          ..
    05/24/2016  05:37 PM               115 hello.cpp
                   1 File(s)            115 bytes
                   2 Dir(s)  571,343,446,016 bytes free
    
    

    日期和其他详细信息在你的计算机上会有所不同。The dates and other details will differ on your computer. 如果看不到源代码文件 hello.cpp,请确保已更改为所创建的“c:\hello”目录 。If you don't see your source code file, hello.cpp, make sure you've changed to the c:\hello directory you created. 在记事本中,请确保将源文件保存在此目录中。In Notepad, make sure that you saved your source file in this directory. 另请确保保存的源代码扩展名为 .cpp,而不是 .txtAlso make sure that you saved the source code with a .cpp file name extension, not a .txt extension.

  6. 在开发人员命令提示下,输入 cl /EHsc hello.cpp 来编译程序。At the developer command prompt, enter cl /EHsc hello.cpp to compile your program.

    cl.exe 编译器会生成包含已编译代码的 .obj 文件,然后运行链接器来创建名为 basic.exe 的可执行程序。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:

    c:\hello>cl /EHsc hello.cpp
    Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25017 for x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    hello.cpp
    Microsoft (R) Incremental Linker Version 14.10.25017.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:hello.exe
    hello.obj
    

    备注

    如果遇到错误(例如“‘cl’无法识别为内部或外部命令、可操作的程序或批处理文件”、错误 C1034 或错误 LNK1104),则说明未正确设置开发人员命令提示。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.

    备注

    如果收到其他编译器或链接器错误或警告,请检查源代码以更正任何错误,然后保存它并再次运行编译器。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. 若要运行 hello.exe 程序,请在命令提示处输入 helloTo run the hello.exe program, at the command prompt, enter hello.

    该程序显示以下文本并退出:The program displays this text and exits:

    Hello, world, from Visual C++!
    

    恭喜,你已通过命令行工具编译并运行了 C++ 程序。Congratulations, you've compiled and run a C++ program by using the command-line tools.

后续步骤Next steps

此“Hello, World”示例与 C++ 程序一样简单。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.

你可以使用本演练中的步骤来创建自己的 C++ 代码,而不是键入所示的示例代码。You can use the steps in this walkthrough to build your own C++ code instead of typing the sample code shown. 还可通过这些步骤生成你在其他位置看到的许多 C++ 代码示例程序。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. 默认情况下,Visual Studio IDE 在用户文件夹的“source\repos”子文件夹中创建项目。By default, the Visual Studio IDE creates projects in your user folder, in a source\repos subfolder. 旧版本可能会将项目放入 Documents\Visual Studio <version>\Projects* 文件夹中。Older versions may put projects in a *Documents\Visual 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

/EHsc 命令行选项指示编译器启用标准 C++ 异常处理行为。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. 有关详细信息,请参阅 /EH(异常处理模型)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. 在本例中,编译器输出一个名为 file1.exe 的程序。In this case, it outputs a program called file1.exe. 若要将名称更改为 program1.exe,请添加 /out 链接器选项:To change the name to program1.exe, add an /out linker option:

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

若要自动捕获更多编程错误,我们建议使用 /W3/W4 警告级别选项进行编译: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

编译器 cl.exe 还有很多选项。The compiler, cl.exe, has many more options. 可以应用这些选项来生成、优化、调试和分析你的代码。You can apply them to build, optimize, debug, and analyze your code. 如需快速列表,请在开发人员命令提示下输入 cl /?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. 有关编译器和链接器选项及用法的详细信息,请参阅 C/C++ 生成参考For more information on compiler and linker options and usage, see C/C++ Building Reference.

可以使用 NMAKE 和生成文件、MSBuild 和项目文件或 CMake 在命令行上配置和生成更复杂的项目。You can use NMAKE and makefiles, MSBuild and project files, or CMake, to configure and build more complex projects on the command line. 有关使用这些工具的详细信息,请参阅 NMAKE 参考MSBuildVisual Studio 中的 CMake 项目For more information on using these tools, see NMAKE Reference, MSBuild, and CMake projects in Visual Studio.

C 和 C++ 语言相似,但并不相同。The C and C++ languages are similar, but not the same. MSVC 编译器使用一个简单的规则来确定在编译代码时使用哪种语言。The MSVC compiler uses a simple rule to determine which language to use when it compiles your code. 默认情况下,MSVC 编译器将以 .c 结尾的文件视为 C 源代码,将以 .cpp 结尾的所有文件视为 C++ 源代码 。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. 要强制编译器将所有文件视为独立于文件扩展名的 C++,请使用 /TP 编译器选项。To force the compiler to treat all files as C++ independent of file name extension, use the /TP compiler option.

MSVC 编译器包括符合 ISO C99 标准的 C 运行时库 (CRT),只有几个较小例外。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. MSVC 编译器弃用了某些过时的库函数和多个 POSIX 函数名。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. 有关详细信息,请参阅 CRT 中的安全功能编译器警告(级别 3)C4996For more information, see Security Features in the CRT and Compiler Warning (level 3) C4996.

请参阅See also

C++ 语言参考C++ Language Reference
项目和生成系统Projects and build systems
MSVC 编译器选项MSVC Compiler Options