For those of us who write C programs in Vim, nothing could be more frustrating than to leave the editor (
shift+ZZ) to compile and run the source code we are working on. Here are a few productivity-enhancing tips in this regard.
The bang “!” symbol allows the execution of arbitrary commands inside the Vim editor. To compile and run the current source code file run,
:! gcc % && ./a.out
% is substituted by the currently opened file. Vim displays the output in a blank shell screen until we press
Enter. Forget not to save the source file (
:w) before you compile since Vim runs the command on the file, not on the buffer content.
In order to compile a specific file,
:!gcc somecode.c -o somecode && ./somecode
:make command can be used to build the source code from the
Makefile. The simplest Makefile would contain,
program gcc hello.c
We can write a Makefile that encompasses our entire project.
The best solution is to associate an hotkey to compile-and-run just like in an IDE. Open
.vimrc (create one if you don’t have) and add,
map <F8> :w <CR> :!gcc % -o %< && ./%< <CR>
Here “:w” saves the current file, and “%<” is the file name without the extension. Now every time you hit F8, Vim compiles the source code, creates the object file (without any file extension) and runs it for us.