Compile and Run C Program From Within VIM

For those of us who write C programs in Vim, nothing could be more frustrating than to leave the editor (:x, :wq, shift+ZZ) to compile and run the source code we are working on. Here are a few productivity-enhancing tips in this regard.

1. “!”
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

Here % 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.

vim-bang-command-gcc

In order to compile a specific file,

:!gcc somecode.c -o somecode && ./somecode

2. “make”
The Vim :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.

3. “keymap”
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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s