I want Vim to execute build the project automatically after I write the buffer to a *.c or *.cpp file. Here is what I've done:

autocmd BufWritePost *.c,*.cpp make

This one works as expected (but the output is noisy; see the bonus question below):

"main.c" 26L, 448C written
:!make  2>&1| tee /var/folders/x0/lrg8j6r535n4lvnfnj6lr2fr0000gn/T/vF0bk92/0
clang -g main.c
               (1 of 1): clang -g main.c
Press ENTER or type command to continue

The problem is, when there is no makefiles in the current directory, an error is thrown:

"test.c" [New] 0L, 0C written
:!make  2>&1| tee /var/folders/x0/lrg8j6r535n4lvnfnj6lr2fr0000gn/T/vtVN9SA/0
make: *** No targets specified and no makefile found.  Stop.
(1 of 1): make: *** No targets specified and no makefile found.  Stop.
Press ENTER or type command to continue

How can I tell autocmd to check if a makefile exists before executing the command?

Bonus question: can I tell autocmd to execute the command quietly? That is, don't show the output of the command, or more preferably, show it in the status line.


1 Answer 1


Indeed filereadable() is how we could detect whether a file exists. Here, you'd want to check filereadable(expand('<amatch>:p:h').'/Makefile')).

In order to check for a Makefile in a directory above the one where your file is, it's findfile() you're looking for.

But beware if you have a lot of files, you won't want to freeze vim every time you save a file among the hundred if not the thousand a project contains. And if you want to do that in the background, you'll have to make sure to not start make several times in parallel.

Also, I don't know if you're aware of it, but single file projects don't need a Makefile. If you're using gnu-make, and if your version of gnu make is properly configured (Mingw one is the only one I'm aware of to be improperly configured), you can just execute :make %< to compile the current file into an executable.

  • Took me a while to figure out: it should be filereadable instead of filereadble or filereadeable :)
    – nalzok
    Sep 1, 2017 at 14:15
  • Oups. Sorry :) I fix my message. Sep 1, 2017 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.