I just ran across this gem in an old Justinhj’s Coding Blog post. Most of the time developers are working on projects that are complex enough to require a make file and for them, Emacs does the right thing when you call 【Meta+x】 compile
by using make -k
as the compile command. Sometimes, though, you have a simple, single file that you’d like to compile and for those you have to type in the compile command by hand after the 【Meta+x】 compile
.
As Justin points out, there’s a better way. You can set the local file variable compile-command
in the source file to the correct compile command. For example, I added this line to the top of the makepw.c
file (that I wrote about here) to control the compilation.
/* -*- compile-command: "gcc -Wall -lcrypto -o makepw makepw.c" -*- */
That works very nicely and any time I make changes or need to recompile it for some reason I can just type 【Meta+x】 compile
and Emacs does the rest for me.
One caveat: Emacs searches for and evaluates file local variables when the file is visited, so if you are starting from scratch you will need to do something like save the file and then do a 【Meta+x】 revert-buffer
to get the variable evaluated. After that, Emacs will set it each time you load the file. It also has the additional benefit of documenting the proper compiler invocation, which may not be obvious because of library dependencies and so on.
I didn’t know this trick and Justin’s post was from 2009 so it’s worthwhile pointing it out again for people like me who weren’t aware of the compile-command
local file variable.
Update: Most of time → Most of the time; worth while → worthwhile