Как запустить программу c через командную строку
Перейти к содержимому

Как запустить программу c через командную строку

  • автор:

Run C++ in command prompt — Windows

I know that everyone uses an IDE nowadays, but I just find it simpler to write my code in notepad++, compile it using a command prompt command, and run it from there too. At least that works for Java and Python. I’ve tried to get my head around how to do that with C++, and haven’t been able to find anything good. Is there any compiler (like Java’s JDK) that I can stick into my path and use the C++ equivalent of javac and java to run and compile my code from CMD?

Note: please don’t post answers and comments about how IDEs are better — I know they are. I’m just used to doing it the old way 😀

14 Answers 14

Steps to perform the task:

First, download and install the compiler.

Then, type the C/C++ program and save it.

Then, open the command line and change directory to the particular one where the source file is stored, using cd like so:

Then, to compile, type in the command prompt:

Finally, to run the code, type:

ib.'s user avatar

codeDEXTER's user avatar

If you’re running Windows then make use of this:

g++ is the name of the compiler and -o is the option needed for creating a .o file. Program (without .cpp suffix) is the exe file and program.cpp is your source file that you want to compile.

Use this shortcut to run the .exe file of the program. This might run in Linux but you may have to use .out suffix instead of .exe . Use this handy batch script to execute your programs on Windows:

save it as cppExecutor.bat

Also you could use the following commands on Unix (Linux and Mac) OS:

If you want to use gcc :

With the shortcut:

JedaiCoder's user avatar

It depends on what compiler you’re using.

For example, if you are using Visual C++ .NET 2010 Express, run Visual C++ 2010 Express Command Prompt from the start menu, and you can simply compile and run the code.

or from the regular command line, you can run vcvars32.bat first to set up the environment. Alternatively search for setvcvars.cmd (part of a FLOSS project) and use that to even locate the installed VS and have it call vcvars32.bat for you.

Please check your compiler’s manual for command lines.

Sure, it’s how most compilers got started. GCC is probably the most popular (comes with most flavors of *nix). Syntax is just gcc my_source_code.cpp , or gcc -o my_executable.exe my_source_code.cpp . It gets more complicated, of course, when you have multiple source files (as in implementation; anything #include d works automatically as long as GCC can find it).

MinGW appears to be a version of GCC for Windows, if that’s what you’re using. I haven’t tried it though.

Pretty sure most IDEs also include a command line interface. I know Visual Studio does, though I have never used it.

KRyan's user avatar

I really don’t see what your problem is, the question is rather unspecific. Given Notepad++ I assume you use Windows.

You have so many options here, from the MinGW (using the GCC tool chain and GNU make ) to using a modern MSVC. You can use the WDK ( ddkbuild.bat/.cmd or plain build.exe ), the Windows SDK ( nmake.exe ), other tools such as premake and CMake, or msbuild that comes with MSVC and the Windows SDK.

I mean the compiler names will differ, cl.exe for MSVC and the WDK and Windows SDK, gcc.exe for MinGW, but even from the console it is customary to organize your project in some way. This is what make and friends were invented for after all.

So to know the command line switches of your particular compiler consult the manual of that very compiler. To find ways to automate your build (i.e. the ability to run a simple command instead of a complex command line), you could sift through the list on Wikipedia or pick one of the tools I mentioned above and go with that.

Side-note: it isn’t necessary to ask people not to mention IDEs. Most professional developers have automated their builds to run from a command line and not from within the IDE (as during the development cycle for example), because there are so many advantages to that approach.

How To Run A C-Program In Command Prompt

randerson112358

Before we begin, if you enjoy my articles and content and would like more content on programming, stocks, machine learning, etc. , then please give this article a few claps, it definitely helps out and I truly appreciate it ! So let’s begin !

In this article I want to show you all how to run a C-Program in command prompt/ line on a Windows operating system! Be sure to install C-Programming compiler first (gcc). If this article is helpful to ya please leave some claps ! I would really appreciate it!

Step0: Install C-Program Compiler (gcc)

You will need a C compiler to do this already installed, I use GCC. https://gcc.gnu.org/. If you are on a Windows computer, you can run the command gcc -v to check if it’s already installed. If gcc is installed then it should display a host of information starting with the sentence “Using built-in specs”.

Step1: Create Your C-Program

Create your C-Program, I have created a simple program that prints “Hello World!” to the screen, and saved it as helloWorld.c . See the code below:

Step2: Open Command Prompt/Line

Open the command prompt by clicking start button → All Apps → Windows System folder → Click Command Prompt. You can see the exact steps here.

Компилятор gcc для программирования на языке Си: запуск кода

Компилятор gcc распространяется по лицензии GNU, Фондом свободного программного обеспечения, для nix-подобных ОС и является C\C++ компилятором, который управляется с помощью командной строки. gcc распространяется с nix системами, так что если вы работаете в ОС Unix или Linux, скорее всего в вашей системе уже установлен gcc.
Чтобы запустить исходный код, с помощью компилятора gcc, просто введите в терминале (командной строке) следующую команду:

После того, как исходный файл будет скомпилирован в исполняемый, на выходе мы получим файл с именем a и расширением *.out — a.out , который можно будет запустить с помощью команды

Перед запуском gcc можно указать в командной строке имя исполняемого файла, который получим на выходе. Для этого необходимо установить параметр -o и присвоить нужное имя файла.

Полностью команда будет выглядеть так:

Опять же, вы можете запустить программу с помощью команды ./outputfile . (Точка и слэш ./ перед именем файла используются для указания текущего каталога.)

Чтобы отображались все предупреждения, необходимо использовать флаг:

Чтобы быть уверенными, что компилятор действительно поддерживает стандарты ANSI, используем флаг:

Если вы хотите, чтобы компилятор рассматривал предупреждения как ошибки, используйте флаг -Werror . В таком случае, если возникнет хотя бы одно предупреждение, вы не получите исполняемый файл.

Если вы хотите, отлаживать исполняемый файл в отладчике GDB, включайте в команду флаг -g .

Это позволит отладчику GDB, дать вам подробную информацию о процессе отладки, в том числе дополнительный код в исполняемый файл.

Математическая библиотека

Если вам нужно использовать функции из математической библиотеки (как правило, функции из заголовочного файла math.h , таких как sin или sqrt ), необходимо явно указать этот файл. Чтобы привязать библиотеку используется флаг -l , после указывается флаг библиотеки m :

Обратите внимание, что в C++ не надо использовать этот флаг.
Если вы используете *nix-подобные системы, вы также можете проверить другие опции компилятора gcc, введя в командную строку следующую команду:

руководство (на английском) к компилятору gcc, или

руководство (на русском) к компилятору gcc.

Создание разделяемых библиотек

Если вы хотите узнать, как создать разделяемую библиотеку в Linux с gcc, прочитайте статью: как создать разделяемую библиотеку на Linux с помощью gcc.

How to Run C and C++ Program in CMD

In this article I will tell you how to run C and C++ program in CMD.

CMD or Command Prompt is a command line interpreter in Windows operating system. Running C and C++ programs using command prompt is useful in case you don’t have an IDE installed in your system.

Things you will need

You must have a C or C++ compiler like GCC, Visual C++, etc. already installed in your system. If you don’t have any, you can easily get them by searching on Google.

How to Run C and C++ Program in CMD

1.Before running programs we must set the path of compiler. So, first right click on Computer icon and go to Properties option.

2. Click on Advance system settings and then Environment Variables.

How to Run C and C++ Program in CMD

3. A new window will open, there click on New button. In Variable name filed enter path and in Variable value filed enter the path of the bin folder of compiler.

How to Run C and C++ Program in CMD

4. You can find the path of bin folder by going to the directory where you have installed the compiler.

5. After that click all OK buttons to save the information.

6. Press Win+R keys to open Run. Type cmd and press enter to open command prompt.

7. Now change the directory to where you have saved your C or C++ program file. Lets say you have saved the program on Desktop then type cd desktop and press enter.

8. Now for compiling the program type gcc filename. Here filename is the name of the program file. I have used gcc command because I have installed GCC compiler in my system. The command will change if you are using any other compiler, like for Turbo C++ it will be tcc, for Borland C++ it will be bcc and so on.

9. For running the program just type the name of the source file without .c or .cpp extension and press enter.

10. If you have followed steps properly then you can see the output.

How to Run C and C++ Program in CMD

Comment below if you have any doubts regarding above how to run C and C++ program in CMD article.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *