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

Как запустить код с через консоль

  • автор:

How can I compile and run C/C++ code in a Unix console or Mac terminal?

How can I compile/run C or C++ code in a Unix console or a Mac terminal?

Peter Mortensen's user avatar

19 Answers 19

If it is a simple single-source program,

where the source file is foo.c, foo.cpp, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.

Running the executable just built is the same as running any program — but you will most often need to specify the path to the executable as the shell will only search what is in $PATH to find executables, and most often that does not include the current directory ( . ).

So to run the built executable foo :

Peter Mortensen's user avatar

Peter Mortensen's user avatar

This is the command that works on all Unix machines. I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.

-o is the letter O, not zero

lab21 will be your executable file

iterative.cpp is your C++ file

After you run that command, type the following in the terminal to run your program:

Peter Mortensen's user avatar

Komengem's user avatar

Two steps for me:

Peter Mortensen's user avatar

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

On Mac OS X (by default) this will display the following colon separated search path:

So any executable in the listed directories can by run just by typing in their name. For example:

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

Similarly if I am in the same directory as MyProgram I need to use a «current directory» relative path. The current directory you are in is the period character followed by a slash. For example:

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a «bin» directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn’t already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in

/bin to be used in preference to system executables your should reorder the export statement as follows:

LibreBay

Статьи про ОС Ubuntu. Языки программирования Си и C++.
Инструменты разработки и многое другое.

понедельник, 5 декабря 2016 г.

Как скомпилировать программу на C/C++ в Ubuntu

ubuntu terminal

Помню, когда я только начинал программировать, у меня возник вопрос: «Как скомпилировать программу на C в Ubuntu?» Для новичков это не легкая задача, как может показаться на первый взгляд.

Мой путь изучения C начался с бестселлера «Брайан Керниган, Деннис Ритчи, Язык программирования C, 2-е издание». Там рассказывается как скомпилировать программу в операционной системе Unix, но этот способ не работает в Linux. Авторы книги выкрутились, написав следующее:

Текстовый редактор gedit

Для написания первых программ подойдет обычный, используемый по умолчанию в Ubuntu, текстовый редактор с подсветкой синтаксиса — gedit.

Запуск текстового редактора
Рис. 1. Запуск текстового редактора.

Первой программой по традиции является «Hello, World!», выводящее приветствие на экран:

Печатаем или копируем текст программы в gedit и сохраняем в файл Hello.c , например, на рабочий стол. Не самое лучше место для сохранения, но это позволит рассмотреть случай, когда в имени директории содержится пробел.

Программа hello, World!
Рис. 2. Программа hello, World.

Компиляция программы на C

Теперь запускаем терминал, можно через Dash, а можно с помощью горячих клавиш <ctrl> + <Alt> + <T> . Здесь в начале установим инструменты сборки, куда входят необходимые компиляторы gcc для языка C и g++ для языка C++:

Для установки требуется ввести пароль, при вводе которого может сложиться впечатление, что ничего не происходит, но на самом деле терминал просто в целях безопасности не отображает символы.

Далее в терминале нам необходимо перейти в директорию, куда сохранили файл с текстом программы. Перемещение выполняется командой cd (англ. change directory — изменить каталог). Чтобы воспользоваться командой в начале пишется cd , затем через пробел путь , куда нужно перейти.

Для перехода на рабочий стол, команда будет следующей:

Обратите внимание на символ обратной косой черты \ в имени директории Рабочий стол . Обратная косая экранирует пробел, и сообщает команде cd , что пробел и следующие за ним символы являются частью имени. Символ

в начале пути обозначает путь до домашней папки пользователя.

Для просмотра содержимого директории применяется команда ls (сокращение от англ. list).

Работа в терминале
Рис. 3. Работа в терминале.

Команда компиляции для программы на C выглядит следующим образом:

  • gcc — компилятор для языка программирования C;
  • -Wall — ключ вывода всех предупреждений компилятора;
  • -o hello — с помощью ключа -o указывается имя выходного файла;
  • hello.c — имя нашего исходного файла, который компилируем.

В завершение запустим hello , вводом имени программы с префиксом ./ :

Префикс ./ сообщает терминалу о необходимости выполнить программу с заданным именем в текущем каталоге. (Точка — это условное название текущего каталога.)

Работа в терминале, продолжение
Рис. 4. Работа в терминале, продолжение.

Компиляция программы на С++

Программы на C++ компилируются аналогично, как и программы на C. «Hello, World!» на C++ можно написать так:

Сохраняем текст программы в файл под именем hello2.cpp . Таким образом, команда компилирования будет иметь вид:

Для запуска результата вводим в терминале:

Заключение

Данный способ позволяет скомпилировать программу лишь из одного файла с исходным кодом. Но этого вполне достаточно, чтобы начать изучение языков программирования C/C++ по книгам или по статьям в интернете.

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.

С++ как запустить эту программу в консоли компьютера? Можете подробно объяснить?

с командной строки запустить, добавив аргумент.
C:/Users/. /ConsoleApplication1.exe "print this message"
Или создать ярлык и в поле Обьект дописать в конце чтобы вышло
C:/Users/. /ConsoleApplication1.exe "print this message"

Второе — в самой программе system("pause") должно быть перед return 0
Иначе вы ничего не успеете увидеть.

Чтобы запустить данную программу на C++ в консоли компьютера, вам потребуется выполнить следующие шаги:

Откройте интегрированную среду разработки (IDE) или текстовый редактор и создайте новый файл с расширением ".cpp". Например, вы можете назвать его "main.cpp".

Скопируйте предоставленный вами код программы в созданный файл "main.cpp".

Сохраните файл "main.cpp".

Откройте командную строку или терминал на вашем компьютере.

Перейдите в директорию, где находится файл "main.cpp", используя команды cd (change directory) для смены текущей директории.

Компиляция программы: В командной строке введите команду для компиляции программы. Например, для компиляции программы с использованием компилятора GNU g++, введите следующую команду:

Это скомпилирует файл "main.cpp" и создаст исполняемый файл с именем "program".

Запуск программы: После успешной компиляции введите команду для запуска программы:Замените <аргумент> на текст, который вы хотите вывести вертикально. Например:Программа выведет каждую букву текста "Hello" в вертикальной ориентации.

Результат: В консоли вы увидите вывод программы, в данном случае вертикально выведенный текст.

Я пишу в visual studio code, я его уже скомпилировал, но в консоле он не запускается.

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

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