Estimated reading time: 1 minutes

Compiling C source in vim

The fabulous Miss Biddulph asks via the EADS Linux list:

Is there a way to make vim compile C files without a Makefile?

A quick phone call later and we know that Laura wishes to emulate make’s behaviour where calling make my_code without a Makefile will attempt to build my_code from my_code.c. vim’s default :make command doesn’t quite do the trick as it just calls make without any arguments.

vim allows us to set options for specific file types only using the :autocmd command, and this is the perfect time to use it. We will set the value of makeprg, which vim uses as the command to run with :make, for all C and C++ files.

autocmd FileType c,cpp
    \ if empty(glob("[Mm]akefile")) |
    \   setlocal makeprg=make\ %< |
    \ endif

The %< in our makeprg definition refers to the current file with its extension stripped. We specifically only change the behaviour if no Makefile exists so that we don’t interfere with the normal usage of the :make command.


Authenticate this page by pasting this signature into Keybase.

Have a suggestion or see a typo? Edit this page