Thursday, May 14, 2009

Writing quick C++ programs in emacs without a makefile



Cheetah by Storm Crypt

Often when programming in C++ (or many other languages) it's desirable to write a quick program, usually a console application, to test something quickly. Working in developer studio, it takes an amount of fiddling and clicking large enough that you may not want to bother.

Working in emacs and MingW32 (or Microsoft's CL.exe) I can quickly create a CPP file, and then compile it. To compile a program though you need to either write a makefile, or build up a complex g++ command line.

Rather than do either of those I make a helloworld.cpp file which can be built like this:

g++ helloworld.cpp -g -o helloworld.exe

So I hit

M-x compile

then type in the above to compile and link it.

However there's a better way. You can add the compile command as the first line of the file as a file local variable.

// -*- compile-command:"g++ helloworld.cpp -g -o helloworld.exe"; -*-

Now I can hit the compile and it works right away, between sessions. No makefile or project settings in sight, and now there are minimal barriers involved in creating a simple test program beyond copy and pasting the file.

3 comments:

ashawley said...

if you name your file helloworld.cc and you are using GNU make, you can have the compile-command be just: "make helloworld".

Justin said...

ashawley: Did not know that, thanks!

ashawley said...

Yeah, and then wouldn't it be great if you could just use this?

// -*- compile-command: (concat compile-command (file-name-nondirectory (file-name-sans-extension (buffer-file-name)))); -*-Nevermind, even if it worked it's way too long to be cute.