Compile cpp file windows

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

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.

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.

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

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.

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.

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.

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

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.

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.

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.

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.

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.

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.

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:

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.

Читайте также:  Команда копирования linux командная строка

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.

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 source\repos subfolder. Older versions may put projects in a *Documents\Visual Studio \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.

Пошаговое руководство. Компиляция собственной программы на языке 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.

В этом пошаговом руководстве приводятся инструкции по созданию программы на языке C++ в стиле «Hello, Wolrd» в текстовом редакторе с последующей компиляцией из командной строки. 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 вместо командной строки, см. статью Пошаговое руководство. Работа с проектами и решениями (C++) или Использование интегрированной среды разработки Visual Studio для разработки приложений для настольных систем на языке 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++ или Build Tools командной строки для 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 Edition, и все они могут поддерживать разработку на C и C++. Versions available include the free Visual Studio Community edition, and all can support C and C++ development. Сведения о скачивании и установке Visual Studio см. в статье Установка поддержки C++ в Visual Studio. For information on how to download and install Visual Studio, see Install C++ support in Visual Studio.

Build Tools для 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. Чтобы установить только средства командной строки, найдите Build Tools для 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.

Читайте также:  Не работают передние аудио выходы windows

Открытие командной строки разработчика Open a developer command prompt

Если вы установили Visual Studio 2017 или более поздней версии в Windows 10, откройте меню «Пуск» и выберите Все приложения. 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.

Если вы установили Microsoft Visual C++ Build Tools 2015 в Windows 10, откройте меню Пуск и выберите Все приложения. If you have installed Microsoft Visual C++ Build Tools 2015 on Windows 10, open the Start menu and choose All apps. Прокрутите вниз и откройте папку Microsoft Visual C++ Build Tools. Scroll down and open the Visual C++ Build Tools folder. Выберите элемент Командная строка Native Tools x86 Visual C++ 2015, чтобы открыть окно командной строки. 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.

Затем убедитесь в том, что командная строка разработчика 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:

Возможно, существуют различия в текущем каталоге или номерах версий. 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 C++ в Visual Studio или Microsoft Visual C++ Build Tools. 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 Studio. For 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

В окне командной строки разработчика введите 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 both your source file and the compiled program get created.

В окне командной строки введите notepad hello.cpp . Enter notepad hello.cpp in the command prompt window.

Когда Блокнот предложит создать файл, выберите Да. Choose Yes when Notepad prompts you to create a new file. Откроется пустое окно Блокнота, в котором можно ввести код для файла hello.cpp. This step opens a blank Notepad window, ready for you to enter your code in a file named hello.cpp.

В окне блокнота введите следующие строки кода: 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.

Сохраните файл. Save your work! В Блокноте, в меню Файл выберите Сохранить. In Notepad, on the File menu, choose Save.

Поздравляем, вы создали исходный файл C++ hello.cpp, который готов к компиляции. Congratulations, you’ve created a C++ source file, hello.cpp, that is ready to compile.

Вернитесь к окну командной строки разработчика. 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:

Даты и некоторые другие данные будут отличаться на вашем компьютере. 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 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. Также убедитесь, что файл исходного кода был сохранен с расширением имени файла .cpp , а не .txt . And make sure that you saved the source code with a .cpp file name extension, not a .txt extension. Если открыть Блокнот из командной строки с помощью команды notepad hello.cpp , файл исходного кода автоматически сохраняется в текущем каталоге в виде файла .cpp . 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. Если Блокнот открыть другим способом, его поведение также будет другим. По умолчанию Блокнот добавляет расширение .txt в новые файлы при их сохранении. 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. Чтобы сохранить файл с расширением .cpp в Блокноте, выберите Файл > Сохранить как. To save your file with a .cpp extension in Notepad, choose File > Save As. В диалоговом окне Сохранение файла перейдите к папке C:\hello в элементе управления иерархического представления каталогов. 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 (*.*). Введите hello.cpp в элемент управления «Поле ввода» Имя файла и нажмите кнопку Сохранить, чтобы сохранить файл. Enter hello.cpp in the File name edit control, and then choose Save to save the file.

Читайте также:  Команда конфигурации системы windows

В командной строке разработчика введите cl /EHsc hello.cpp , чтобы скомпилировать свою программу. At the developer command prompt, enter cl /EHsc hello.cpp to compile your program.

Компилятор cl.exe создаст OBJ-файл, содержащий скомпилированный код, а затем запустит компоновщик для создания исполняемой программы с именем hello.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:

Если вы получаете сообщение об ошибке, например «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.

Чтобы запустить программу hello.exe, в командной строке введите hello . To run the hello.exe program, at the command prompt, enter hello .

Программа выводит следующий текст и закрывается: The program displays this text and exits:

Поздравляем, вы скомпилировали и запустили программу 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 создает проекты в папке пользователя во вложенной папке source\repos. By default, the Visual Studio IDE creates projects in your user folder, in a source\repos subfolder. Более старые версии могут помещать проекты в папку Документы\Visual Studio \ Проекты*. Older versions may put projects in a Documents\Visual Studio \ 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 и файлы makefile, 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, MSBuild и Проекты CMake в Visual Studio. 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 как исходные файлы на языке С, а файлы с расширением .cpp — как исходные файлы на языке С++. 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. Если указан параметр компилятора /TP, компилятор будет рассматривать все файлы как исходные файлы на языке С++ вне зависимости от расширения. To force the compiler to treat all files as C++ independent of file name extension, use the /TP compiler option.

Компилятор MSVC содержит библиотеку времени выполнения C (CRT), которая соответствует стандарту ISO C99 с небольшими исключениями. 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. Некоторые устаревшие функции библиотеки и несколько имен функций POSIX не рекомендуется использовать в компиляторе MSVC. 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) C4996. For more information, see Security Features in the CRT and Compiler Warning (level 3) C4996.

Оцените статью