演练:在命令行上编译 C 程序Walkthrough: Compile a C program on the command line

Visual C++ 包括一个 C 编译器,可用于创建从基本的控制台程序到完整的 Windows 桌面应用程序、移动应用等的各种程序。Visual C++ includes a C compiler that you can use to create everything from basic console programs to full Windows Desktop applications, mobile apps, and more.

本演练演示如何使用文本编辑器创建“Hello, World”样式的 C 程序,然后在命令行上对其进行编译。This walkthrough shows how to create a basic, "Hello, World"-style C program by using a text editor, and then compile it on the command line. 如果想在命令行上使用 C++,请参阅演练:在命令行上编译本机 C++ 程序If you'd rather work in C++ on the command line, see Walkthrough: Compiling a Native C++ Program 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.

先决条件Prerequisites

若要完成本演练,你必须已安装 Visual Studio 和可选的 Visual C++ 组件,或已安装 Visual Studio 生成工具。To complete this walkthrough, you must have installed either Visual Studio and the optional Visual C++ components, or the Build Tools for Visual Studio.

Visual Studio 是功能强大的集成开发环境,它支持用于多种语言和平台的功能齐全的编辑器、资源管理器、调试程序和编译器。Visual Studio is a powerful integrated development environment that supports a full-featured editor, resource managers, debuggers, and compilers for many languages and platforms. 有关这些功能以及如何下载和安装 Visual Studio(包括免费的 Visual Studio Community 版本)的信息,请参阅安装 Visual StudioFor information on these features and how to download and install Visual Studio, including the free Visual Studio Community edition, see Install Visual Studio.

Visual Studio 生成工具只安装生成 C 和 C++ 程序所需的命令行工具集、编译器、工具和库。The Build Tools for Visual Studio version of Visual Studio installs only the command-line toolset, the 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 toolset, download Build Tools for Visual Studio from the Visual Studio downloads page and run the installer. 在 Visual Studio 安装程序中,选择“C++ 生成工具”工作负荷,然后选择“安装” 。In the Visual Studio installer, select the C++ build tools workload, and choose Install.

必须先验证是否已安装工具以及是否可以从命令行访问它们,然后才能在命令行上生成 C 或 C++ 程序。Before you can build a C or C++ program on the command line, you must verify that the tools are installed, and that 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 some preparation. 你需要开发人员命令提示窗口,这是常规命令提示窗口,其中设置了所有必需的环境变量 。You need a developer command prompt window, which is a regular command prompt window that has all the required environment variables set. 幸运的是,Visual C++ 为你安装了快捷方式来启动开发人员命令提示,这些命令提示为命令行生成设置了环境。Fortunately, Visual C++ installs shortcuts for you to launch developer command prompts that have 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 to find the right shortcut to use.

备注

开发人员命令提示快捷方式自动为编译器和工具以及所有必需的标头和库设置正确的路径。A developer command prompt shortcut automatically sets the correct paths for the compiler and tools, and for any required headers and libraries. 对于每个生成配置,其中一些值有所不同。Some of these values are different for each build configuration. 如果不使用其中一个快捷方式,则必须自己设置这些环境值。You must set these environment values yourself if you don't use one of the shortcuts. 有关详细信息,请参阅 为命令行生成设置路径和环境变量For more information, see Set the Path and Environment Variables for Command-Line Builds. 因为生成环境很复杂,所以我们强烈建议使用开发人员命令提示快捷方式,而不要自己生成。Because the build environment is complex, we strongly recommend you use a developer command prompt shortcut instead of building your own.

根据使用的 Visual Studio 版本,操作说明会有所不同。These instructions vary depending on which version of Visual Studio you are using. 若要查看 Visual Studio 首选项的文档,请使用“版本”选择器控件 。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.

在 Visual Studio 2019 中打开开发人员命令提示Open a developer command prompt in Visual Studio 2019

如果已在 Windows 10 上安装 Visual Studio 2019,请打开“开始”菜单,然后向下滚动并打开“Visual Studio 2019”文件夹(而不是 Visual Studio 2019 应用) 。If you have installed Visual Studio 2019 on Windows 10, open the Start menu, and then scroll down and open the Visual Studio 2019 folder (not the Visual Studio 2019 app). 选择“VS 2019 开发人员命令提示”以打开命令提示窗口 。Choose Developer Command Prompt for VS 2019 to open the command prompt window.

如果使用其他版本的 Windows,请在“开始”菜单或“开始”页中查找包含开发人员命令提示快捷方式的 Visual Studio 工具文件夹。If you're using a different version of Windows, look in your Start menu or Start page for a Visual Studio tools folder that contains a developer command prompt shortcut. 还可以使用 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.

在 Visual Studio 2017 中打开开发人员命令提示Open a developer command prompt in Visual Studio 2017

如果已在 Windows 10 上安装 Visual Studio 2017,请打开“开始”菜单,然后向下滚动并打开“Visual Studio 2017”文件夹(而不是 Visual Studio 2017 应用) 。If you have installed Visual Studio 2017 on Windows 10, open the Start menu, and then scroll down and open the Visual Studio 2017 folder (not the Visual Studio 2017 app). 选择“VS 2017 开发人员命令提示”以打开命令提示窗口 。Choose Developer Command Prompt for VS 2017 to open the command prompt window.

如果运行其他版本的 Windows,请在“开始”菜单或“开始”页中查找包含开发人员命令提示快捷方式的 Visual Studio 工具文件夹。If you're running a different version of Windows, look in your Start menu or Start page for a Visual Studio tools folder that contains a developer command prompt shortcut. 还可以使用 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.

在 Visual Studio 2015 中打开开发人员命令提示Open a developer command prompt in Visual Studio 2015

如果已在 Windows 10 上安装 Microsoft Visual C++ 2015 生成工具,请打开“开始”菜单,然后向下滚动并打开“Visual C++ 生成工具”文件夹 。If you have installed Microsoft Visual C++ Build Tools 2015 on Windows 10, open the Start menu, and then 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 工具文件夹。If you're running a different version of Windows, look in your Start menu or Start page for a Visual Studio tools folder that contains a developer command prompt shortcut. 还可以使用 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.

接下来,验证 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... ]

当前目录或版本号可能有所不同,具体取决于 Visual C++ 的版本和所安装的任何更新。There may be differences in the current directory or version numbers, depending 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 2017 或更高版本,请尝试重新安装 Visual Studio 安装程序中的“使用 C++ 的桌面开发”工作负荷 。If you're using Visual Studio 2017 or later, try reinstalling the Desktop development with C++ workload in the Visual Studio installer. 有关详细信息,请参阅在 Visual Studio 中安装 C++ 支持For details, see Install C++ support in Visual Studio. 或者,从 Visual Studio 下载页重新安装生成工具。Or, reinstall the Build Tools from the Visual Studio downloads page. 在操作生效前,请不要继续进行下一部分。Don't go on to the next section until this works. 有关 Visual Studio 的安装和故障排除的详细信息,请参阅安装 Visual StudioFor more information about installing and troubleshooting Visual Studio, 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.

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

  1. 在开发人员命令提示窗口中,输入 cd c:\ 以将当前工作目录更改为 C: 驱动器的根目录。In the developer command prompt window, enter cd c:\ to change the current working directory to the root of your C: drive. 接下来,输入 md c:\simple 以创建目录,然后输入 cd c:\simple 以更改为该目录。Next, enter md c:\simple to create a directory, and then enter cd c:\simple to change to that directory. 此目录将保存源文件和编译的程序。This directory will hold your source file and the compiled program.

  2. 在开发人员命令提示下输入 notepad simple.cEnter notepad simple.c at the developer command prompt. 在弹出的记事本警报对话框中,选择“是”以在工作目录中创建新的 simple.c 文件 。In the Notepad alert dialog that pops up, choose Yes to create a new simple.c file in your working directory.

  3. 在记事本中,输入以下代码行:In Notepad, enter the following lines of code:

    #include <stdio.h>
    
    int main()
    {
        printf("Hello, World! This is a native C program compiled on the command line.\n");
        return 0;
    }
    
  4. 在“记事本”菜单栏上,选择“文件” > “保存”以将 simple.c 保存到工作目录 。On the Notepad menu bar, choose File > Save to save simple.c in your working directory.

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

    C:\simple>dir
     Volume in drive C has no label.
     Volume Serial Number is CC62-6545
    
     Directory of C:\simple
    
    10/02/2017  03:46 PM    <DIR>          .
    10/02/2017  03:46 PM    <DIR>          ..
    10/02/2017  03:36 PM               143 simple.c
                   1 File(s)            143 bytes
                   2 Dir(s)  514,900,566,016 bytes free
    
    

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

  6. 若要编译程序,请在开发人员命令提示下输入 cl simple.cTo compile your program, enter cl simple.c at the developer command prompt.

    你可以在编译器显示的多行输出信息中看到可执行程序的名称 simple.exe:You can see the executable program name, simple.exe, in the lines of output information that the compiler displays:

    c:\simple>cl simple.c
    Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25017 for x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    simple.c
    Microsoft (R) Incremental Linker Version 14.10.25017.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:simple.exe
    simple.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 at the top of this page to look for the error number.

  7. 若要运行程序,请在命令提示下输入 simpleTo run your program, enter simple at the command prompt.

    程序将在显示以下文本后退出:The program displays this text and then exits:

    Hello, World! This is a native C program compiled on the command line.
    

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

后续步骤Next steps

此“Hello, World”示例是最简单的 C 程序。This "Hello, World" example is about as simple as a C program can get. 现实世界中的程序具有头文件和更多源文件,且库中有链接,因此可以执行有用的任务。Real world programs have header files and more source files, link in libraries, and do useful work.

你可以使用本演练中的步骤生成自己的 C 代码,而不是键入所示的示例代码。You can use the steps in this walkthrough to build your own C code instead of typing the sample code shown. 你还可以生成在其他位置看到的许多 C 代码示例程序。You can also build many C code sample programs that you find elsewhere. 若要编译包含其他源代码文件的程序,请在命令行上将它们全部输入,例如:To compile a program that has additional source code files, enter them all on the command line, like:

cl file1.c file2.c file3.c

编译器输出名为 file1.exe 的程序。The compiler outputs a program called file1.exe. 若要将名称更改为 program1.exe,请添加 /out 链接器选项:To change the name to program1.exe, add an /out linker option:

cl file1.c file2.c file3.c /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 file1.c file2.c file3.c /link /out:program1.exe

编译器 cl.exe 具有更多可用于生成、优化、调试和分析代码的选项。The compiler, cl.exe, has many more options you can apply 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 和项目文件在命令行上配置和生成更复杂的项目。You can use NMAKE and makefiles, or MSBuild and project files to configure and build more complex projects on the command line. 有关如何使用这些工具的详细信息,请参阅 NMAKE 参考MSBuildFor more information on using these tools, see NMAKE Reference and MSBuild.

C 和 C++ 语言相似,但并不相同。The C and C++ languages are similar, but not the same. Microsoft C/C++ 编译器 (MSVC) 使用简单的规则确定在编译代码时要使用的语言。The Microsoft C/C++ compiler (MSVC) 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 all files that end in .c as C source code, and all files that end in .cpp as C++ source code. 若要强制编译器将所有文件视为与文件扩展名无关的 C,请使用 /TC 编译器选项。To force the compiler to treat all files as C non-dependent of file name extension, use the /TC compiler option.

MSVC 与 ISO C99 标准兼容,但不严格相容。MSVC is compatible with the ISO C99 standard, but not strictly compliant. 在大多数情况下,可移植的 C 代码将按预期方式进行编译和运行。In most cases, portable C code will compile and run as expected. Visual C++ 支持 ISO C11/C17 中的更改。Visual C++ provides support for the changes in ISO C11/C17. 若要使用 C11/C17 支持进行编译,请使用编译器标志 /std:c11/std:c17To compile with C11/C17 support, use the compiler flag /std:c11 or /std:c17. MSVC 已弃用某些库函数和 POSIX 函数名。Certain library functions and POSIX function names are deprecated by MSVC. 这些函数仍然受支持,但首选名称已更改。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++)Walkthrough: Creating a Standard C++ Program (C++)
C 语言参考C Language Reference
项目和生成系统Projects and build systems
兼容性Compatibility