Компиляция через командную строку c windows

What command does one have to enter at the command line in Windows 7 to compile a basic C program? Like I am literally wondering what you type in the command prompt, to compile a .c file. I tried...

What command does one have to enter at the command line in Windows 7 to compile a basic C program?

Like I am literally wondering what you type in the command prompt, to compile a .c file.

I tried:

> gcc foo.c

But it says:

'gcc' is not recognized as an internal or external command, 
 operable program or batch file.

I also tried:

> minGW foo.c

But I got back:

 'minGW' is not recognized as an internal or external command, 
  operable program or batch file.

I have a path environment variable set to where MinGW is installed:

C:Program Files (x86)CodeBlocksMinGWbin

I can’t really find any information on where I’m going wrong, and can’t find anything in the official MinGW documentation, as it seems like this is something so simple, sort of an embarrassing question, that it’s figured people know what to do?

Peter Mortensen's user avatar

asked May 19, 2012 at 1:48

Finding Nemo 2 is happening.'s user avatar

2

It indicates it couldn’t find gcc.exe.

I have a path environment variable set to where MinGW is installed

Maybe you haven’t set the path correctly?

echo %path%

shows the path to gcc.exe? Otherwise, compilation is similar to Unix:

gcc filename.c -o filename

Peter Mortensen's user avatar

answered May 19, 2012 at 2:09

P.P's user avatar

8

I’ve had this problem and couldn’t find why it kept happening. The reason is simple: Once you have set up the environment paths, you have to close the CMD window, and open it again for it be aware of new environment paths.

Peter Mortensen's user avatar

answered Feb 24, 2014 at 11:32

Herz3h's user avatar

Herz3hHerz3h

1011 silver badge2 bronze badges

1

First:

Add your minGW’s bin folder directory ( ex: Cmingw64bin ) in System variables => Path. visual example


Compile:

.c: gcc filename.c -o desire

.cpp: g++ filename.cpp -o desire


Run:

desire/ or ./desire

answered Jan 10, 2019 at 3:52

AharrFaris's user avatar

AharrFarisAharrFaris

911 silver badge5 bronze badges

0

Just set the environment variable to the EXACT path to gcc.exe like this:

C:Program Files (x86)CodeBlocksMinGWbingcc.exe

pb2q's user avatar

pb2q

57.6k18 gold badges145 silver badges146 bronze badges

answered Sep 11, 2012 at 7:44

mak's user avatar

makmak

1,3441 gold badge13 silver badges20 bronze badges

1

I encountered the same error message after unpacking MinGW archives to C:MinGW and setting the path to environment variable as C:MinGWbin;.

When I try to compile I get this error!

gcc: error: CreateProcess: No such file or directory

I finally figured out that some of the downloaded archives were reported broken while unpaking them to C:MinGW (yet I ignored this initially).
Once I deleted the broken files and re-downloaded the whole archives again from SourceForge, unpacked them to C:MinGW successfully the error was gone, and the compiler worked fine and output my desired hello.exe.

I ran this:

gcc hello.c -o hello

The result result was this (a blinking underscore):

_

Peter Mortensen's user avatar

answered Oct 9, 2012 at 2:54

Kunle's user avatar

KunleKunle

111 bronze badge

I had the same problem with .c files that contained functions (not main() of my program). For example, my header files were «fact.h» and «fact.c», and my main program was «main.c» so my commands were like this:

E:proj> gcc -c fact.c

Now I had an object file of fact.c (fact.o). after that:

E:proj>gcc -o prog.exe fact.o main.c

Then my program (prog.exe) was ready to use and worked properly. I think that -c after gcc was important, because it makes object files that can attach to make the program we need. Without using -c, gcc ties to find main in your program and when it doesn’t find it, it gives you this error.

Peter Mortensen's user avatar

answered Jan 19, 2015 at 10:48

S.Ma.Gh's user avatar

You can permanently include the directory of the MinGW file, by clicking on My Computer, Properties, Advanced system settings, Environment variables, then edit and paste your directory.

jgillich's user avatar

jgillich

68.5k6 gold badges55 silver badges83 bronze badges

answered Apr 7, 2015 at 21:32

filmon's user avatar

Instead of setting the %PATH% you may enter your msys shell. In standard msys and mingw installation gcc is in path, so you can run gcc or which gcc.

I have a batch file sh.bat on my Windows 7, in %PATH%:

C:langmsysbinsh.exe --login %*

Whenever I want to use gcc I enter cmd, then sh, then gcc. I find it very convenient.

When working with linux originated software avoid spaced directories like Program Files. Install them rather to Program_Files. The same regards to tools that you may want to run from msys environment.

answered Sep 20, 2012 at 8:58

Jarekczek's user avatar

JarekczekJarekczek

7,2763 gold badges44 silver badges66 bronze badges

If you pasted your text into the path variable and added a whitespace before the semicolon, you should delete that and add a backslash at the end of the directory (;C:Program Files (x86)CodeBlocksMinGWbin

answered Jan 4, 2013 at 17:49

Kai Steffes's user avatar

I once had this kind of problem installing MinGW to work in Windows, even after I added the right System PATH in my Environment Variables.

After days of misery, I finally stumbled on a thread that recommended uninstalling the original MinGW compiler and deleting the C:MinGW folder and installing TDM-GCC MinGW compiler which can be found here.

You have options of choosing a 64/32-bit installer from the download page, and it creates the environment path variables for you too.

answered Oct 7, 2014 at 13:54

Feyisayo Sonubi's user avatar

Feyisayo SonubiFeyisayo Sonubi

1,0425 gold badges15 silver badges27 bronze badges

Where is your gcc?

My gcc is in «C:Program FilesCodeBlocksMinGWbin».

"C:Program FilesCodeBlocksMinGWbingcc" -c "foo.c"
"C:Program FilesCodeBlocksMinGWbingcc" "foo.o" -o "foo 01.exe"

Peter Mortensen's user avatar

answered Jul 10, 2015 at 19:53

Amir's user avatar

AmirAmir

1,57017 silver badges24 bronze badges

I am quite late answering this question (5 years to be exact) but I hope this helps someone.

I suspect that this error is because of the environment variables instead of GCC. When you set a new environment variable you need to open a new Command Prompt! This is the issue 90% of the time (when I first downloaded GCC I was stuck with this for 3 hours!) If this isn’t the case, you probably haven’t set the environment variables properly or you are in a folder with spaces in the name.

Once you have GCC working, it can be a hassle to compile and delete every time. If you don’t want to install a full ide and already have python installed, try this github project: https://github.com/sophiadm/notepad-is-effort
It is a small IDE written with tkinter in python. You can just copy the source code and save it as a .py file

answered May 21, 2017 at 18:37

dwmyfriend's user avatar

dwmyfrienddwmyfriend

2341 silver badge10 bronze badges

In Windows 10, similar steps can be followed in other versions of windows.

Right Click on «My Computer» select Properties, Goto Advanced System Settings -> Advanced -> Select «Environment Variables..» .

Find «Path» select it and choose edit option -> Click on New and add «C:MinGWbin» (or the location of gcc.exe, if you have installed at some other location) -> Save and restart command prompt. Gcc should work.

answered Jan 18, 2018 at 5:15

Mayur Naravani's user avatar

Компиляция приложения из командной строки

Последнее обновление: 02.06.2012

Что делать, если не установлена Visual Studio, но так хочется что-нибуль скомпилировать.

Если установлена платформа NET и установлен .NET SDK, то это не проблема. Приложения можно скомпилировать из командной строки,
воспользовавшись утилитой csc.exe. Найти эту утилиту можно в каталоге C:WindowsMicrosoft.NETFramework[Требуемая версия].

Для начала напишем в любом текстовом редакторе простое приложение и сохраним его в файл HelloWorld.cs:

using System;
namespace HelloWorld
{
	class HelloWorld
	{
		static void Main()
		{
			Console.Write("Введите свое имя:");
			string name = Console.ReadLine();
			Console.WriteLine("Привет {0} !", name);
			Console.ReadLine();
		}
	}
}

Теперь скомпилируем и запустим его. Допустим, путь в командной строке установлен на текущий каталог нашего файла HelloWorld.cs. Тогда
введем в командную строку следующую команду (в данном случае у меня установлен 4-й фреймворк в папке v4.0.30319):

C:WindowsMicrosoft.NETFrameworkv4.0.30319csc.exe HelloWorld.cs

Если ошибок при компиляции не возникло, то в одном каталоге с HelloWorld.cs мы увидим скомпилированный файл HelloWorld.exe.

Параметры компиляции

Компилятор может принимать следующие выходные параметры:

Параметр

Описание

/out

Присваивает имя выходной сборки. По умолчанию присваивается то же имя, что и у файла кода cs

/target:exe

Создает консольное приложение. Используется по умолчанию

/target:library

Позволяет создать библиотеку dll

/target:winexe

Позволяет создать графическое приложение. При этом консоль скрывается.

/target:module

Позволяет создать модуль

Теперь создадим простейшее графическое приложение:

using System;
using System.Windows.Forms;
namespace HelloWorld
{
	public class Program
	{
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Form1());
		}
	}
	class Form1 : Form
	{
		TextBox textBox1;
		Button button1;
		
		public Form1()
		{
			//Создаем текстовое поле
			textBox1=new TextBox();
            textBox1.Location = new System.Drawing.Point(50, 50);
			this.Controls.Add(textBox1);
			//Создаем кнопку
			button1 = new Button();
			button1.Location = new System.Drawing.Point(60, 90);
			button1.Text = "Кнопка";
			button1.Click+=button1_Click;
			this.Controls.Add(button1);
		}
		
		private void button1_Click(object sender, EventArgs e)
		{
			if(textBox1.Text=="")
			{
				MessageBox.Show("Введите текст в текстовое поле");
			}
			else
			{
				MessageBox.Show(textBox1.Text);
			}
		}
	}	
}

Скомпилируем его с помощью строки:C:WindowsMicrosoft.NETFrameworkv4.0.30319csc.exe /target:winexe WindowWorld.cs.
И после запуска мы увидим нашу форму. Если бы мы не использовали target:winexe, то также скомпилировали бы графическое приложение, только тогда
при запуске была видна также и консоль.

При компиляции у нас может быть ситуация, когда у нас несоклько исходных файлов, и нам нужно создать из них одно приложени.
Тогда все эти файлы либо перечисляются при компиляции (csc.exe WindowWorld.cs File1.cs File2.cs File3.cs), либо если надо включить все файлы текущего
каталога, то можно использовать следующую запись: csc.exe *.cs.

Также при компиляции может возникнуть необходимость включить ссылку на другую сборку. В предыдущем примере использовались ссылки из сборки
System.Windows.Forms.dll. Однако все ссылки на нее, как и на еще несколько распространенных сборок, компилятр включает по умолчанию. Ссылки на
большинство других сборок придется включать с помощью записи типа:csc.exe /reference:System.Windows.Forms.dll WindowWorld.cs. Если
нужно включить несколько сборок, то они перечисляются друг за другом через точку с запятой:

csc.exe /reference:System.Windows.Forms.dll;System.Drawing.dll  WindowWorld.cs

title description ms.custom ms.date helpviewer_keywords ms.assetid

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

Use the Microsoft C++ compiler from a command prompt.

conceptual

03/25/2021

native code [C++]

Visual C++, native code

compiling programs [C++]

command-line applications [C++], native

b200cfd1-0440-498f-90ee-7ecf92492dc0

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.

[!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 Use the MSVC toolset from the command line. 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 or later, 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 or later, 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:

    C:Program Files (x86)Microsoft Visual Studio2017Enterprise>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. 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:

    #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.

    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:

    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.

    [!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:

    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
    

    [!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:

    Hello, world, from Visual C++!
    

    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

title description ms.custom ms.date helpviewer_keywords ms.assetid

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

Use the Microsoft C++ compiler from a command prompt.

conceptual

03/25/2021

native code [C++]

Visual C++, native code

compiling programs [C++]

command-line applications [C++], native

b200cfd1-0440-498f-90ee-7ecf92492dc0

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.

[!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 Use the MSVC toolset from the command line. 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 or later, 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 or later, 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:

    C:Program Files (x86)Microsoft Visual Studio2017Enterprise>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. 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:

    #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.

    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:

    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.

    [!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:

    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
    

    [!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:

    Hello, world, from Visual C++!
    

    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

Время прочтения
16 мин

Просмотры 37K

Частенько нет необходимости запускать тяжеловесную IDE Visual Studio для компиляции небольших приложений, проведения каких-либо тестов кода, не требующего полномасштабной отладки. В подобных случаях можно оперативно собрать приложение в консольном режиме, используя возможности предоставляемые компилятором от Microsoft (cl.exe) и запускными модулями IDE (devenv.exe, msdev.exe). Далее приводится код файлов сценариев (cmd) интерпретатора командной строки Windows, который с небольшими изменениями каждый может настроить под себя, с учётом путей к Visual Studio в своей системе.

Компиляция cpp-файлов

Код сценария vc++_compile_and_link.cmd

:: --------------------------------------------------------------------------- ::
:: Перед использованием сценария рекомендуется задать системные переменные:    ::
:: sVSPath     - путь к корневому каталогу Visual C++,                         ::
:: sVSPathName - путь к основному исполнимому файлу Visual C++                 ::
:: (либо раскомментировать и отредактировать sVSPath, sVSPathName ниже в файле.::
:: --------------------------------------------------------------------------- ::
echo off
cls

echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 

:: -------------------------------------- ::
::     Имена исходников (через пробел)    ::
:: -------------------------------------- ::
set gavSrc=MySource1.cpp MySource2.cpp


:: -------------------------------------- ::
:: Дополнительно, если необходимо, для Qt ::
:: - заголовочный файл,содержащий Q_OBJECT::
:: из него будет сгенерирован moc_xxx.cpp ::
:: -------------------------------------- ::
::set gavSrcQtMoc=gavQtSignalSlot.h
set gavSrcQtMoc=""

:: -------------------------------------- ::
:: Версия компилятора:                    ::
::    6 - VC6,                            ::
::    8 - VC8 (2005),                     ::
::    9 - VC9,                            ::
::   10 - VC10 (2010)                     ::
::   11 - VC11 (2012)                     ::
:: -------------------------------------- ::
set iCompVer=11


:: -------------------------------------- ::
:: Режим компиляции:                      ::
::    0 - release,                        ::
::    1 - debug,                          ::
::    2 - генерирует прототипы функций    ::
::        (без компиляции)                ::
:: -------------------------------------- ::
set iModeComp=1

:: -------------------------------------- ::
::  Флаги наличия библиотеки:             ::
::      0 - нет, 1 - есть                 ::
:: -------------------------------------- ::
set bLibQt=0
set bLibCrt=0
set bLibBoost=0

:: -------------------------------------- ::
:: Режим линковки с Qt:                   ::
::    0 - shared (динамическая),          ::
::    1 - static (статическая)            ::
:: -------------------------------------- ::
set iModeQt=0

:: -------------------------------------- ::
:: Флаги специальных WINDDK               ::
::    0 - не используется                 ::
::    1 - WINDDK для Win2000, WinXP       ::
::        (в этом случае д.б. верно заданы::
::         gavIncPathDdkXP,gavLibPathDdkXP::
::         - см. ниже)                    ::
:: -------------------------------------- ::
set iWinddk=0

:: -------------------------------------- ::
::    Дополнительные флаги компилятора    ::
::   ( дефайны задавать так: -Dдефайн )   ::
:: -------------------------------------- ::
::set gavCompilFlags=-Dtest


:: -------------------------------------- ::
::     Подсистема приложения (одна из)    ::
:: -------------------------------------- ::
:: Win32 character-mode application: 
set gavSubsystem=CONSOLE
:: Application does not require a console:
::set gavSubsystem=WINDOWS
:: Device drivers for Windows NT:
::set gavSubsystem=NATIVE
:: Application that runs with the POSIX subsystem in Windows NT:
::set gavSubsystem=POSIX
:: Application that runs on a Windows CE device:
::set gavSubsystem=WINDOWSCE



:: -------------------------------------- ::
::          Пути к Visual Studio.         ::
::          !!! без кавычек !!!           ::
:: -------------------------------------- ::
:: VS6 (!! Путь к компилятору VS6 д.б. коротким и без пробелов - иначе ошибка линковки)
if %iCompVer%==6 set sVSPath=C:ProgsVC98
if %iCompVer%==6 set sVSPathName=%sVSPath%bincl.exe

:: VS8 
if %iCompVer%==8 set sVSPath=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 8VC
if %iCompVer%==8 set sVSPathName=%sVSPath%bincl.exe

:: VS9
if %iCompVer%==9 set sVSPath=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 9.0VC
if %iCompVer%==9 set sVSPathName=%sVSPath%bincl.exe

:: VS10
if %iCompVer%==10 set sVSPath=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 10.0VC
if %iCompVer%==10 set sVSPathName=%sVSPath%bincl.exe
                   :: доп.пути для VS2010:
if %iCompVer%==10 set gavIncPathMy=%SYSTEMDRIVE%Program FilesMicrosoft SDKsWindowsv7.0AInclude
if %iCompVer%==10 set gavLibPathMy=%SYSTEMDRIVE%Program FilesMicrosoft SDKsWindowsv7.0ALib

:: VS11
if %iCompVer%==11 set sVSPath=%SYSTEMDRIVE%Program Files (x86)Microsoft Visual Studio 11.0VC
if %iCompVer%==11 set sVSPathName=%sVSPath%bincl.exe
                   :: доп.пути для VS2010:
if %iCompVer%==11 set gavIncPathMy=%SYSTEMDRIVE%Program Files (x86)Windows Kits8.0Includeum
if %iCompVer%==11 set gavIncPathMy2=%SYSTEMDRIVE%Program Files (x86)Windows Kits8.0IncludeShared
if %iCompVer%==11 set gavLibPathMy=%SYSTEMDRIVE%Program Files (x86)Windows Kits8.0IncludeLib
if %iCompVer%==11 set gavLibPathMy2=%SYSTEMDRIVE%Program Files (x86)Windows Kits8.0Libwin8umx86
::if %iCompVer%==11 set gavLibPathMy2=%SYSTEMDRIVE%Program Files (x86)Windows Kits8.0Libwin8umx64

echo Compilator version: VC%iCompVer%
echo Compilator path: %sVSPathName%

:: -------------------------------------- ::
::              Пути к Boost              ::
:: -------------------------------------- ::
set BOOST_ROOT=C:Progsboostboost_1_49_0


:: -------------------------------------- ::
::     Настройка путей к подключаемым     ::
::  файлам.   Каждый путь должен быть     ::
::         отдельной переменной !         ::
:: -------------------------------------- ::
set gavIncPathVS="%sVSPath%include"
set gavIncPathQt="%QTDIR%include"
set gavIncPathBoost="%BOOST_ROOT%"
set gavIncPathDdkCrt="C:ProgsWINDDK2600.1106inccrt"
set gavIncPathDdkXP="C:ProgsWINDDK2600.1106incw2k"

if not "%gavIncPathMy%"=="" (set gavIncPathAll=-I"%gavIncPathMy%" 
                             if not "%gavIncPathMy2%"=="" (
                                                           set gavIncPathAll=-I"%gavIncPathMy%" -I"%gavIncPathMy2%"
                                                          )
                            )
if %iWinddk%==1 (set gavIncPathAll=%gavIncPathAll% -I%gavIncPathDdkCrt% -I%gavIncPathDdkXP%)
if not %gavIncPathVS%=="" (set gavIncPathAll=%gavIncPathAll% -I%gavIncPathVS%)
if %bLibQt%==1 (if not %gavIncPathQt%=="" (set gavIncPathAll=%gavIncPathAll% -I%gavIncPathQt%))
if %bLibBoost%==1 (if not %gavIncPathBoost%=="" (set gavIncPathAll=%gavIncPathAll% -I%gavIncPathBoost%))
echo Include pathes: %gavIncPathAll%


:: -------------------------------------- ::
::  Настройка путей к библиотечным (.lib) ::
::  файлам.   Каждый путь должен быть     ::
::         отдельной переменной !         ::
:: -------------------------------------- ::
set gavLibPathDdkXP=C:ProgsWINDDK2600.1106libwxpi386
set gavLibPathVS=%sVSPath%lib

set gavLibPathAll=""
if %iWinddk%==1 (set gavLibPathAll=%gavLibPathAll% /LIBPATH:"%gavLibPathDdkXP%")
if not "%gavLibPathVS%"=="" (set gavLibPathAll=%gavLibPathAll% /LIBPATH:"%gavLibPathVS%")
if not "%gavLibPathMy%"=="" (set gavLibPathAll=%gavLibPathAll% /LIBPATH:"%gavLibPathMy%"
                             if not "%gavLibPathMy2%"=="" (
                                                           set gavLibPathAll=%gavLibPathAll% /LIBPATH:"%gavLibPathMy%" /LIBPATH:"%gavLibPathMy2%"
                                                          )
                            )

set gavLibPathBoost="%BOOST_ROOT%stagelib"
if %bLibBoost%==1 (if not %gavLibPathBoost%=="" (set gavLibPathAll=%gavLibPathAll% /LIBPATH:%gavLibPathBoost%))

set gavLibPathQtReleaseShared="%QTDIR%libreleaseshared"
set gavLibPathQtReleaseStatic="%QTDIR%libreleasestatic"
set gavLibPathQtDebugShared="%QTDIR%libdebugshared"
set gavLibPathQtDebugStatic="%QTDIR%libdebugstatic"
if %bLibQt%==1 (
                 if %iModeComp%==0 (
                                    if %iModeQt%==0 (
                                                     echo Qt mode: release shared
                                                     set gavLibPathAll=%gavLibPathAll% /LIBPATH:%gavLibPathQtReleaseShared%
                                                    )
                                    if %iModeQt%==1 (
                                                     echo Qt mode: release static
                                                     set gavLibPathAll=%gavLibPathAll% /LIBPATH:%gavLibPathQtReleaseStatic%
                                                    )
                                   )
                 if %iModeComp%==1 (
                                    if %iModeQt%==0 (
                                                     echo Qt mode: debug shared
                                                     set gavLibPathAll=%gavLibPathAll% /LIBPATH:%gavLibPathQtDebugShared%
                                                    )
                                    if %iModeQt%==1 (
                                                     echo Qt mode: debug static
                                                     set gavLibPathAll=%gavLibPathAll% /LIBPATH:%gavLibPathQtDebugStatic%
                                                    )
                                   )
               )
echo Lib pathes: %gavLibPathAll%

:: -------------------------------------- ::
::      Файлы библиотеки run-time.        ::
:: При необходимости добавить сюда нужные ::
:: -------------------------------------- ::
set gavLibFilesCrt=""
if %bLibCrt%==1 (set gavLibFilesCrt=user32.lib ole32.lib Gdi32.lib Ws2_32.lib Imm32.lib Comdlg32.lib Winspool.lib Advapi32.lib)
if not "%gavLibFilesCrt%"=="" (set gavLibFilesAll=%gavLibFilesCrt%)

:: -------------------------------------- ::
::         Файлы библиотеки Qt.           ::
:: -------------------------------------- ::
set gavLibFilesQtShared=qtmain.lib qt-mt333.lib
set gavLibFilesQtStatic=qtmain.lib qt-mt.lib

if %bLibQt%==1 (
                if %iModeQt%==0 (set gavLibFilesAll=%gavLibFilesAll% %gavLibFilesQtShared%)
                if %iModeQt%==1 (set gavLibFilesAll=%gavLibFilesAll% %gavLibFilesQtStatic%)
               )

echo Lib files: %gavLibFilesAll%


:: -------------------------------------- ::
::     Настройка режимов компиляции       ::
:: -------------------------------------- ::
if %iModeComp%==0 (
               set gavLinkMode=/RELEASE
               :: для DLL: set gavCompMode=/MD
               set gavCompMode=/MT
               set gavOptimize=/O2 /GA
              )

if %iModeComp%==1 (
               set gavLinkMode=/DEBUG
               :: для DLL: set gavCompMode=/MDd
               set gavCompMode=/MTd
               ::set gavOptimize=/Od /ZI
               set gavOptimize=/Od /Z7
              ) 

if %iModeComp%==2 (
               set gavLinkMode=
               set gavCompMode=
               set gavOptimize=/Zg
              ) 

if %bLibQt%==1 (if %iModeQt%==1 (set gavCompMode=/MDd))

:: -------------------------------------- ::
::    Настройка подсистемы приложения     ::
:: -------------------------------------- ::
if not %gavSubsystem%=="" (set gavLinkSubsys=/SUBSYSTEM:%gavSubsystem%)


:: -------------------------------------- ::
::         Настройка компилятора          ::
:: -------------------------------------- ::
if %bLibQt%==1 (
                if %iModeQt%==0 (set gavCompilFlags=%gavCompilFlags% -DQT_DLL)
               )

:: -------------------------------------- ::
::        Удаление старых файлов          ::
:: -------------------------------------- ::
set gavOldObj=%gavSrc:.cpp=.obj,%
set gavOldObj=%gavOldObj:.c=.obj,%
set gavOldAsm=%gavOldObj:.obj=.asm%
for /F "tokens=1" %%A in ("%gavSrc%") do (set gavMainName=%%A)
set gavMainName=%gavMainName:.cpp=%
set gavMainName=%gavMainName:.c=%
set gavDelExt= %gavMainName%.exe, %gavMainName%.pdb, %gavMainName%.ilk, %gavOldObj% %gavOldAsm% __vc++_%gavMainName%.log
echo. 
echo Deleting old files: %gavDelExt% ...
echo. 
del %gavDelExt%
echo. 
echo ------------------
echo Compiling start...
echo ------------------
echo. 

if %bLibQt%==1 (if not %gavSrcQtMoc%=="" (
echo ------------------
echo Mocing file... 
echo ------------------
echo on
%QTDIR%binmoc %gavSrcQtMoc% -o moc_%gavSrcQtMoc%.cpp
@echo off
set gavSrc=%gavSrc% moc_%gavSrcQtMoc%.cpp
))

echo on
"%sVSPathName%" /EHsc %gavIncPathAll% %gavCompilFlags% /Fa %gavSrc% %gavCompMode% %gavOptimize% /link %gavLinkSubsys% %gavLinkMode% %gavLibPathAll% %gavLibFilesAll%>"__vc++_%gavMainName%.log"

@echo off
echo. 
echo ------------------
echo Compiling end...
echo ------------------
echo. 
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
:: -------------------------------------- ::
pause

Основные параметры, которые следует

однократно

настроить в вышеприведённом сценарии:
1) в разделе «Пути к Visual Studio» необходимо задать пути к файлам различных версий Visual Studio (если у вас их установлено несколько):

  • sVSPath — путь к основному каталогу Visual Studio т.е. к корневому каталогу, в котором содержатся все прочие подкаталоги для данной версии VS.
  • gavIncPathMy — возможно для VS 11.0 потребуется задать свои пути к подключаемым заголовочным файлам.

2) в разделе «Пути к Boost» можно задать BOOST_ROOT — путь к коревому каталогу библиотеки Boost (если она у вас установлена).
3) в разделе «Настройка путей к подключаемым файлам» при необходимости можно задать пути к заголовочным файлам Qt, WinDDK.
4) в разделе «Настройка путей к библиотечным (.lib) файлам» задаются пути к файлам библиотек (в частности для WinDDK).

Реже может возникнуть необходимость настроить следующие параметры под конкретный проект:
iCompVer — версия используемого компилятора (6 — для VC6, 8 — VC8 (2005), 9 — VC9, 10 — VC10 (2010), 11 — VC11 (2012).
gavLibFilesQtShared — имена .lib-файлов для динамически подключаемой библиотеки Qt;
gavLibFilesQtStatic — имена .lib-файлов для статически линкуемой библиотеки Qt.
gavLibFilesCrt — имена .lib-файлов для стандартных динамических библиотек, используемых в Windows.
iModeQt — режим линковки библиотеки Qt.
gavCompMode — флаги режима компиляции (однопоточные, многопоточные и т.п.).
gavOptimize — флаги оптимизации кода компилятором.

Чаще всего приходится менять параметры:
gavSrc — имена файлов с исходным кодом, разделённые пробелом (если их несколько).
bLibQt — флаг (0/1) необходимости использовать библиотеку Qt при сборке приложения.
bLibCrt — флаг (0/1) необходимости использовать стандартные CRT-библиотеки Windows при сборке приложения.
bLibBoost — флаг (0/1) необходимости использовать библиотеку Boost при сборке приложения.
gavSubsystem — подсистема создаваемого приложения: CONSOLE — консольное, WINDOWS — с графическим интерфейсом.

Результат (ошибки, сообщения) компиляции можно просмотреть в файле __vc++_XXX.log, где XXX — имя основного исходного файла

Сборка cpp-приложения из файлов проектов

Аналогично без запуска IDE можно собрать проект, используя файлы проектов и воркспейсов (dsp, dsw).

Код сценария vc++_dsp_dsw_compile.cmd

:: Перед использованием сценария рекомендуется задать системную переменную sVSPathName,
:: указывающую путь к основному исполнимому файлу Visual Studio либо раскомментировать 
:: и отредактировать sVSPathName ниже в этом файле...
@echo off
cls

echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 
:: -------------------------------------- ::
:: имя файла проекта (dsp) или вокспейса (dsw):
set sPrjFile=MyWorkspace.dsp

:: -------------------------------------- ::
:: Режим компиляции: 0 - release, 1 - debug, 2 - release и debug:
set iMode=2

:: -------------------------------------- ::
:: Режим обработки файлов: 
::        0 - удаление промежуточных файлов, 
::        1 - перекомпиляция изменившихся фйлов,
::        2 - полная пересборка проекта (рекомендуется при iMode=2)
set iSubMode=2


:: -------------------------------------- ::
:: Имя конфигурации:
if %sPrjFile:.dsp=% == %sPrjFile% (
   set sPrjName=%sPrjFile:.dsw=%
  ) ELSE (
   set sPrjName=%sPrjFile:.dsp=%
  )

:: Имя конфигурации - для режима release: 
set sConfigNameRelease="%sPrjName% - Win32 Release"
:: Имя конфигурации - для режима debug: 
set sConfigNameDebug="%sPrjName% - Win32 Debug"


:: -------------------------------------- ::
:: пути к Visual Studio:
:: set sVSPathName=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 6.0CommonMSDev98BinMSDEV.EXE
:: set sVSPathName=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 8Common7IDEVCExpress.exe
:: set sVSPathName=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 9.0Common7IDEdevenv.exe

:: -------------------------------------- ::
:: Подрежим:

if %iSubMode%==0 (
               set iCompMode=/CLEAN
              )

if %iSubMode%==1 (
               set iCompMode=
              ) 

if %iSubMode%==2 (
               set iCompMode=/REBUILD
              ) 

:: -------------------------------------- ::
echo. 
echo ---------------------------------
echo [%sPrjName%]: compiling start...
echo ---------------------------------
echo. 
@echo off

if %iMode%==0 (
:: режим release: 
echo [%sPrjName%]: configuration mode:
echo     %sConfigNameRelease%
echo on
"%sVSPathName%" %sPrjFile% /MAKE %sConfigNameRelease% %iCompMode% /OUT __vc++_compile_release.log
)

@echo off
if %iMode%==1 (
:: режим debug: 
echo [%sPrjName%]: configuration mode:
echo     %sConfigNameDebug%
echo on
"%sVSPathName%" %sPrjFile% /MAKE %sConfigNameDebug% %iCompMode% /OUT __vc++_compile_debug.log
)
 
@echo off
if %iMode%==2 (
:: режим release и debug: 
echo [%sPrjName%]: configuration modes: 
echo     %sConfigNameRelease%
echo     %sConfigNameDebug%
echo on
"%sVSPathName%" %sPrjFile% /MAKE %sConfigNameRelease% %iCompMode% /OUT __vc++_compile_release.log
"%sVSPathName%" %sPrjFile% /MAKE %sConfigNameDebug%   %iCompMode% /OUT __vc++_compile_debug.log
)


@echo off
echo. 
echo ---------------------------------
echo [%sPrjName%]: compiling end.
echo ---------------------------------
echo. 
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
:: -------------------------------------- ::
pause

Компиляция cs-файлов

Вышерассмотренный функционал реализуем и для C#:

Код сценария vc#_compile_and_link.cmd

:: --------------------------------------------------------------------------- ::
:: Перед использованием сценария рекомендуется задать системные переменные:    ::
:: sVSPath     - путь к корневому каталогу Visual C#,                          ::
:: sVSPathName - путь к основному исполнимому файлу Visual C#                  ::
:: (либо отредактировать sVSPath, sVSPathName ниже в файле.::
:: --------------------------------------------------------------------------- ::
echo off
cls

echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 

:: -------------------------------------- ::
::     Имена исходников (через пробел)    ::
:: -------------------------------------- ::
set gavSrc=Program.cs


:: -------------------------------------- ::
:: Режим компиляции:                      ::
::    0 - release,                        ::
::    1 - debug,                          ::
:: -------------------------------------- ::
set iModeComp=1

:: -------------------------------------- ::
::     Подсистема приложения (одна из)    ::
:: -------------------------------------- ::
:: /target:exe                    Построить консольный исполняемый файл (по умолчанию) (Краткая форма: /t:exe)
set gavSubsystem=exe
:: /target:winexe                 Построить исполняемый файл Windows  (Краткая форма: /t:winexe)
::set gavSubsystem=winexe
:: /target:library                Построить библиотеку (Краткая форма: /t:library)
::set gavSubsystem=library
:: /target:module                 Построение модуля, который может быть добавлен в другую сборку (Краткая форма: /t:module)
::set gavSubsystem=module
:: /target:appcontainerexe        Построение исполняемого файла Appcontainer (Краткая форма: /t:appcontainerexe)
::set gavSubsystem=appcontainerexe
:: /target:winmdobj               Построение промежуточного файла среды выполнения Windows, используемого WinMDExp (Краткая форма: /t:winmdobj)
::set gavSubsystem=winmdobj

:: -------------------------------------- ::
::      ПЛАТФОРМА приложения (одна из)    ::                                  
::    (x86, Itanium, x64, arm или anycpu. ::
::      Платформа по умолчанию: anycpu.)  ::
:: -------------------------------------- ::
set gavPlatform=anycpu

:: -------------------------------------- ::
::    Дополнительные флаги компилятора    ::
:: -------------------------------------- ::
::set gavCompilFlags=

:: -------------------------------------- ::
::          Пути к Visual Studio.         ::
::          !!! без кавычек !!!           ::
:: -------------------------------------- ::
 set sVSPath=%WINDIR%Microsoft.NETFrameworkv4.0.30319
 set sVSPathName=%sVSPath%csc.exe

:: -------------------------------------- ::
::     Настройка путей к подключаемым     ::
::  файлам.   Каждый путь должен быть     ::
::         отдельной переменной !         ::
:: -------------------------------------- ::
set gavIncPathVS="%sVSPath%"

if not "%gavIncPathMy%"=="" (set gavIncPathAll=-I"%gavIncPathMy%")
if not %gavIncPathVS%=="" (set gavIncPathAll=%gavIncPathAll% -I%gavIncPathVS%)
echo Include pathes: %gavIncPathAll%


:: -------------------------------------- ::
::  Настройка путей к библиотечным (.lib) ::
::  файлам.   Каждый путь должен быть     ::
::         отдельной переменной !         ::
:: -------------------------------------- ::
set gavLibPathVS=%sVSPath%
if not "%gavLibPathVS%"=="" (set gavLibPathAll=/lib:"%gavLibPathVS%")
if not "%gavLibPathMy%"=="" (set gavLibPathAll=%gavLibPathAll% /lib:"%gavLibPathMy%")

echo Lib pathes: %gavLibPathAll%

:: -------------------------------------- ::
::      Файлы библиотеки run-time.        ::
:: При необходимости добавить сюда нужные ::
:: -------------------------------------- ::
:: set gavLibFilesCrt=user32.lib ole32.lib Gdi32.lib Ws2_32.lib Imm32.lib Comdlg32.lib Winspool.lib Advapi32.lib
::set gavLibFilesCrt=""
if not "%gavLibFilesCrt%"=="" (set gavLibFilesAll=%gavLibFilesCrt%)

echo Lib files: %gavLibFilesAll%


:: -------------------------------------- ::
::     Настройка режимов компиляции       ::
:: -------------------------------------- ::
if %iModeComp%==0 (
               set gavCompilFlags=%gavCompilFlags% /D:_RELEASE 
               set gavCompMode=/debug-
               set gavOptimize=/optimize+
              )

if %iModeComp%==1 (
               set gavCompilFlags=%gavCompilFlags% /D:_DEBUG 
               set gavCompMode=/debug+
               set gavOptimize=/optimize-
              ) 

:: -------------------------------------- ::
::    Настройка подсистемы приложения     ::
:: -------------------------------------- ::
if not %gavSubsystem%=="" (set gavLinkSubsys=/t:%gavSubsystem%)


:: -------------------------------------- ::
set gavDelExt=*.obj, *.exe, *.log, *.pdb
echo. 
echo Deleting old files: %gavDelExt% ...
echo. 
del %gavDelExt%
echo. 
echo ------------------
echo Compiling start...
echo ------------------
echo. 

echo on
"%sVSPathName%" %gavDefine% %gavCompilFlags% %gavCompMode% %gavOptimize% %gavLinkSubsys% /utf8output /fullpaths /platform:%gavPlatform% %gavLibPathAll% %gavLibFilesAll% %gavSrc%>__vc#_compile.log

@echo off
echo. 
echo ------------------
echo Compiling end...
echo ------------------
echo. 
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
:: -------------------------------------- ::
pause

Сборка cs-приложения из файлов солюшенов (sln) и проектов (csproj)

Код сценария vc#_sln_csproj_compile.cmd

:: Перед использованием сценария рекомендуется задать системную переменную sVSPathName,
:: указывающую путь к основному исполнимому файлу Visual Studio либо раскомментировать 
:: и отредактировать sVSPathName ниже в этом файле...
@echo off
cls

echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 
:: -------------------------------------- ::
:: имя файла проекта (.csproj) или вокспейса (sln):
set sPrjFile=MyProject.csproj

:: -------------------------------------- ::
:: Режим компиляции: 0 - release, 1 - debug, 2 - release и debug:
set iMode=2

:: -------------------------------------- ::
:: Режим обработки файлов: 
::        0 - удаление промежуточных файлов, 
::        1 - перекомпиляция изменившихся фйлов,
::        2 - полная пересборка проекта (рекомендуется при iMode=2)
set iSubMode=2


:: -------------------------------------- ::
:: Имя конфигурации:
if %sPrjFile:.sln=% == %sPrjFile% (
   set sPrjName=%sPrjFile:.sln=%
  ) ELSE (
   set sPrjName=%sPrjFile:.csproj=%
  )

:: Имя конфигурации - для режима release: 
:: set sConfigNameRelease="Release|Win32"
set sConfigNameRelease="Release"
:: Имя конфигурации - для режима debug: 
:: set sConfigNameDebug="Debug|Win32"
set sConfigNameDebug="Debug"


:: -------------------------------------- ::
:: пути к Visual Studio:
set sVSPathName=%SYSTEMDRIVE%Program Files (x86)Microsoft Visual Studio11.0Common7IDEdevenv.exe
:: set sVSPathName=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 8Common7IDEVCExpress.exe
:: set sVSPathName=%SYSTEMDRIVE%Program FilesMicrosoft Visual Studio 9.0Common7IDEdevenv.exe

:: -------------------------------------- ::
:: Подрежим:

if %iSubMode%==0 (
               set iCompMode=/Clean
              )

if %iSubMode%==1 (
               set iCompMode=
              ) 

if %iSubMode%==2 (
               set iCompMode=/Rebuild
              ) 

:: -------------------------------------- ::
echo. 
echo ---------------------------------
echo [%sPrjName%]: compiling start...
echo ---------------------------------
echo. 
@echo off

if %iMode%==0 (
:: режим release: 
echo [%sPrjName%]: configuration mode:
echo     %sConfigNameRelease%
echo on
"%sVSPathName%" %sPrjFile% /Build %sConfigNameRelease% /Out __vc#_compile_release.log
)

@echo off
if %iMode%==1 (
:: режим debug: 
echo [%sPrjName%]: configuration mode:
echo     %sConfigNameDebug%
echo on
"%sVSPathName%" %sPrjFile% /Build %sConfigNameDebug%   /Out __vc#_compile_debug.log
)
 
@echo off
if %iMode%==2 (
:: режим release и debug: 
echo [%sPrjName%]: configuration modes: 
echo     %sConfigNameRelease%
echo     %sConfigNameDebug%
echo on
"%sVSPathName%" %sPrjFile% /Build %sConfigNameRelease% /Out __vc#_compile_release.log
"%sVSPathName%" %sPrjFile% /Build %sConfigNameDebug%   /Out __vc#_compile_debug.log
Rem /project lxDbLib.csproj /projectconfig Debug 
)


@echo off
echo. 
echo ---------------------------------
echo [%sPrjName%]: compiling end.
echo ---------------------------------
echo. 
echo -------------------------------------- 
echo ------ %date% [%time%] ------
echo -------------------------------------- 
echo ---------- .:: -=LEXX=- ::. ----------
echo -------------------------------------- 
:: -------------------------------------- ::
pause

На первый взгляд громоздкость данного кода, компенсируется простотой последующей работы в консоли. Всем приятного программирования!!!


Загрузить PDF


Загрузить PDF

В этой статье рассказывается, как скомпилировать программу из исходного кода на языке C с помощью компилятора GNU Compiler (GCC) для Linux или Minimalist Gnu (MinGW) для Windows.

  1. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 1

    1

    В Unix-системе откройте терминал.

  2. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 2

    2

    Введите gcc --version и нажмите Enter. Отобразится версия компилятора C. Если команда не сработала, скорее всего, GCC не установлен.[1]

    • Если компилятор не установлен, почитайте документацию к своему дистрибутиву Linux, чтобы узнать, как скачать соответствующий пакет.
    • Если вы компилируете программу, написанную на языке C++, вместо «gcc» введите «g++».
  3. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 3

    3

    Перейдите в каталог, в котором хранится исходный код.

    • Например, если файл с исходным кодом «main.c» находится в каталоге /usr/wikiHow/source, введите cd /usr/wikiHow/source.
  4. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 4

    4

    Введите gcc main.c -o HelloWorld. Замените «main.c» на имя файла с исходным кодом, а «HelloWorld» замените на имя конечной программы. Программа будет скомпилирована.

    • Если на экране появились сообщения об ошибках, введите gcc -Wall -o errorlog file1.c, чтобы получить дополнительную информацию. Затем в текущем каталоге откройте файл «errorlog»; для этого введите cat errorlog.
    • Чтобы скомпилировать одну программу из нескольких файлов с исходным кодом, введите gcc -o outputfile file1.c file2.c file3.c.
    • Чтобы скомпилировать сразу несколько программ из нескольких файлов с исходными кодами, введите gcc -c file1.c file2.c file3.c.
  5. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 5

    5

    Запустите скомпилированную программу. Введите &# 46;/HelloWorld, где «HelloWorld» замените именем программы.

    Реклама

  1. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 6

    1

    Скачайте Minimalist GNU для Windows (MinGW). Эту версию GCC для Windows довольно легко установить. Установочный файл можно скачать на этом сайте.[2]

  2. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 7

    2

    Запустите установочный файл MinGW.

    • Если файл не запустился автоматически, дважды щелкните по нему в папке для загрузок, а затем нажмите «Установить».
  3. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 8

    3

    Задайте параметры установки и нажмите Continue (Далее).

    • Рекомендуем установить MinGW в папку по умолчанию, а именно в (C:MinGW). Если нужно поменять папку, не выбирайте папку, в названии которой присутствуют пробелы, такую как «Program Files».[3]
  4. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 9

    4

    Выберите компиляторы, которые нужно установить.

    • На левой панели рекомендуем нажать «Basic Setup» (Обычная установка). Затем на правой панели поставьте флажки рядом со всеми перечисленными компиляторами.
    • Более опытные пользователи могут выбрать опцию «All packages» (Все пакеты) и отметить дополнительные компиляторы.
  5. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 10

    5

    Откройте меню Installation (Установка). Оно находится в верхнем левом углу MinGW.

  6. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 11

    6

    Нажмите Apply Changes (Применить изменения).

  7. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 12

    7

    Нажмите Apply (Применить). Компиляторы будут загружены и установлены.

  8. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 13

    8

    В путь к MinGW вставьте системные переменные среды. Сделайте следующее:

    • Нажмите Win+S, чтобы открыть строку поиска, и введите среда.
    • В результатах поиска щелкните по «Изменение системных переменных среды».
    • Нажмите «Переменные среды».
    • Нажмите «Изменить» (под «Пользовательские переменные»).
    • Прокрутите вниз информацию в поле «Значение переменной».
    • Непосредственно под последней записью введите ;C:MinGWbin. Обратите внимание, что если вы установили MinGW в другую папку, введите ;C:путь-к-папкеbin.
    • Дважды нажмите «OK». Еще раз нажмите «OK», чтобы закрыть окно.
  9. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 14

    9

    Откройте командную строку в качестве администратора. Для этого:

    • Нажмите Win+S и введите строка.
    • В результатах поиска щелкните правой кнопкой мыши по «Командная строка» и в меню выберите «Запуск от имени администратора».
    • Нажмите «Да», чтобы разрешить внесение изменений.
  10. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 15

    10

    Перейдите в папку, в которой хранится файл с исходным кодом.

    • Например, если файл с исходным кодом «helloworld.c» находится в папке C:SourcePrograms, введите cd C:SourcePrograms.
  11. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 16

    11

    Введите gcc helloworld.c -o helloworld.exe. Замените «helloworld» на имя файла с исходным кодом и имя программы. По завершении компиляции программы вы вернетесь в командную строку, при этом не будет никаких сообщений об ошибках.[4]

    • Любые ошибки программирования должны быть устранены перед компиляцией программы.
  12. Изображение с названием Compile a C Program Using the GNU Compiler (GCC) Step 17

    12

    Чтобы запустить программу, введите ее имя. Если программа называется helloworld.exe, введите это имя, чтобы запустить программу.

    Реклама

Советы

  • Компиляция кода с помощью флага -g приведет к созданию отладочной информации, которая может быть использована соответствующим отладчиком, например, GDB.
  • Создайте сборочный файл проекта (make-файл), чтобы упростить компиляцию больших программ.
  • Если вы активно используете оптимизацию, помните, что оптимизация по скорости может привести к снижению размера и, иногда, качества (и наоборот).
  • При компиляции программы на языке C++ используйте G++ так же, как вы используете GCC. Помните, что файлы с исходным кодом на языке C++ имеют расширение .cpp, а не .c.

Реклама

Что вам понадобится

  • Компьютер под управлением Linux или Windows
  • Базовые знания GNU/Linux и знание того, как устанавливать приложения
  • Программный код
  • Текстовый редактор (например, Emacs)

Об этой статье

Эту страницу просматривали 72 864 раза.

Была ли эта статья полезной?

Понравилась статья? Поделить с друзьями:
  • Компоненты visual c для windows 10 64 bit
  • Комп не видит сетевую карту на windows 10
  • Компиляция kivy под android на windows
  • Компоненты active directory для windows 10
  • Компиляция kivy в apk в windows