Developing with C/C++ on console

Saturday, Jan 30, 2016
Section: Home / Post
Categories: Developer,
Tags: Bash, C/C++, Linux,


I am taking a High Performance Computing course this semester. For that we have to ssh into the university’s computing cluster. The interface is entirely console based. Now that might seem awesome at first: typing away commands like a “hacker”. And it is awesome. But after a while it gets tiring, particularly when I am writing code.

With C/C++, source files are compiled into an executable. Then the program can be run. This usually takes two sets of commands:

$ g++ <file.cpp> -o <executable_name>
$ ./<executable_name>

But then I discovered the wonders of bash commands.  Bash  is the environment of the Linux terminal. It lets you define functions that you can call later. The function I wrote was:

cpp() {
        local fname=$1
        local exe_name=${fname/.cpp/.exe}
        echo "$(tput setaf 3)Compiling: " $fname "-> " $exe_name"; args=>[${@:2}]$(tput sgr0)"
        g++ $1 -o $exe_name
        ./$exe_name "${@:2}"
}

I put this function in my .bashrc file so it’s available whenever I log in to my terminal. With this function,  I can just pass the .cpp file as an argument along with other command line arguments. The function compiles and runs the source file together:

$ cpp <source_file.cpp> <any arguments>

Viola!



comments powered by Disqus