Use inotify-tools to auto compile code on save with VIM/tmux
Posted on September 22nd, 2013
I wanted a solution where when a file was saved in VIM, gcc got automatically launched with the proper parameters to automatically compile the code and automatically launch the binary. Here is how I did it.
Quick install of tmux, tmuxinator, ruby and rubygems on Raspberry Pi
The setup for tmux and tmuxinator was/is very simple, run the following as root.
apt-get update apt-get install vim apt-get install ruby apt-get install ruby1.9.1-dev (Required step for tmux or you'll get an error like "/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file --mkmf (LoadError)") apt-get install tmux apt-get install rubygems gem update --system gem install tmuxinator
With those tools installed, I can now launch the development environment in split windows, I've got a config for tmux setup with some customised keyboard short cuts.
Auto launch GCC after saving
The top right terminal is running a shell script using inotify-tools to monitor the source code folder. It monitors for changes in any file that doesn't end in SWP or TMP and then executes GCC with the parameters required to build the output.
The script I'm running is:
#!/bin/sh while inotifywait -qq -e create --exclude '\.(swp|txt|tmp)' /pis/src; do sleep 1 gcc /pis/src/main.cpp -o /pis/bin/pistat chmod +x /pis/bin/* done
inotifywait is watching for CREATE event's which are raised when the file is created, hence the sleep 1, this causes us to wait for 1 second for VIM to dump the file to disk before allowing it to compile (if it's not there, GCC can execute before the file contents is saved resulting in errors). There is probably a different event I can subscribe to rather than having the sleep but for now, this works for me.
The chmod is to make the binary ready to execute, as I have another script in the lower window that will automatically launch the binary when the code is compiled in the second window below.
To install inotify-tools, just launch this as root and its ready to run.
apt-get install inotify-tools
I'll probably move the monitor script to to a different tmux window so its not consuming the space and visible to me. I've used the