How To Make Commands For Linux Terminal. Compile and Run Your C Code in One Command

My friend has just started learning C and he was talking about how it was irritating that you couldn’t run the code with one command like you can with Python. I agreed this was irritating, so I decided to take advantage of the customisability of Linux and make a command to do this for you.

Quick: clone this repository, make the setup file executable using “sudo chmod +x setup” and then run “./setup”.

Steps:

1: Create a bash script

Bash is the programming language used by the shell on Linux. You can create a bash script with the extension .sh, but you can also make a file without an extension by starting the file #! /bin/bash to create a bash environment.

$ gedit FILENAME

2: Add your bash code

As I mentioned above, if you have not added the .sh extension to your file make sure to establish a bash environment with #! /bin/bash

#!/bin/bash

filename=${1?Error: no file}

fileCString=$filename'.c'
fileOString=$filename'.o'

 gcc $fileCString -o $fileOString  -lm

 ./$fileOString

Save and exit this file.

3: Move it to your binary executables and change to this directory

$ sudo mv ~/YOURCOMMAND /usr/local/bin/YOURCOMMAND
$ cd /usr/local/bin

You can call the file whatever you’d like but I will call it makeandrun

4: Change the owner of the command to root (sudo)

$ sudo chown root: makeandrun

5: Give file correct permissions

$ sudo chmod 755 makeandrun

755 is shortened from the binaries for the permissions for the owner, group and others for the file. All files have read, write and execute permissions that can be represented as a 3 digit binary value. 111 for permission for all, 000 for permission for none. 7 5 5 is the decimal of 111 101 101, meaning that the owner of the file can read write and execute, whereas the group and other can only read and execute.

6: Run the file

You now have a command for compiling and running C code! Just write the command makeandrun with the c file next to it (without the .c) and it will compile it and then run it.

$ makeandrun yourProgram

Leave a Reply

Your email address will not be published. Required fields are marked *