Insert Title

Jun 04, 2020

Save time by auto-compiling and auto-running your application

Introduction

One of the most important attributes of Linux is being able to customize and automate everything to your needs. When working under a Linux environment, you should take some time to abbreviate and automate tasks and single steps that you do repeatedly; even small “micro-optimizations” will save a lot more time in the long run: After a while, you will see how you can stick together small things to create more complex time-savers.

The first step is writing bash aliases, bash functions and small shell scripts to ease your daily workflow. If you keep setting up your development environment manually everyday (e.g. by opening an editor, a terminal for compiling, etc) don’t go right into creating a huge script for setting this up automatically - usually, this won’t be correct in the first try and you will need way more time to develop this script.

Start small

Instead, start small. For example, if you constantly switch between your editor and the terminal to compile something (or if you keep hitting the compile button in your IDE), use a tool like entr to automate this:

function compile-my-app() {
    cd /path/to/build/folder
    find /path/to/project/source -not \( -path ../.ccls-cache \) -type f -iname \*.cpp | entr make
}

Explanation

entr is a small tool which repeats a given command when a file in a given list of files changes. The find command lists all *.cpp files and feed it into entr, while omitting everything in the .ccls-cache directory. Of course this is just an example, but you can adapt it to your workflow very quickly.

Now by putting this function in your .bashrc, you will be able to start an infinite compile session when you start working on the source code of your application. Constantly switching between your editor and a terminal window (or hitting the build button in your IDE) is no longer needed, giving you more time to do your work.

Of course you can go one step further; if you restart you app after it has been compiled successfully every time anyway, why not add another function for this?

function run-my-app() {
    cd /path/to/build/folder
    echo my-app | entr -r ./my-app
}

Executing run-my-app and compile-my-app will now cause your application to be restarted automatically every time you change a source file.

Conclusion

At first, this might not seem as much of an improvement; however, if you use functions like this for the majority of your workday, you will realize that the typical “compile-try-change-recompile” iteration becomes very fast. Furthermore, since compiling and executing the application happens automatically, you will get rid of some cognitive load and improve your concentration.

Originally, this post was intended to contain a list of useful bash aliases, functions and scripts. We will save this for another day.