1

I am trying to set up Emacs so that when I choose "Compile.." in the menu, Emacs executes "make filename" on the command line. I am trying something like:

(setq compile-command (concat "make " (file-name-sans-extension
                                       buffer-file-name)))

but it doesn't work - it looks like Emacs is is looking for a file-name for the *scratch* buffer, which doesn't have one. Does anyone know how to fix this?

Thanks.

UPDATE: as suggested by Cheeso, a hook fixes the problem. Here is a version that works for me:

(defun cur-file ()
  (file-name-sans-extension
   (file-name-nondirectory (buffer-file-name (current-buffer)))))

(add-hook 'c++-mode-hook
          (lambda()
            (set (make-local-variable 'compile-command)
                 (concat "make " (cur-file)))))
phils
  • 71,335
  • 11
  • 153
  • 198
LazyCat
  • 496
  • 4
  • 14
  • 1
    n.b. You should either accept Cheeso's answer, or post your own solution as an answer and accept that. – phils Apr 10 '12 at 05:41

1 Answers1

4

Yes - a couple options for you.

  • Simple: define a file-local variable. In the header comment of your file just include something like

     // -*- compile-command: "gcc -Wall -O3 -o f file.c" -*-
    

    For more details, see: https://stackoverflow.com/a/4540977/48082

  • More elaborate - there is a module called smarter-compile.el available on the marmalade repo. It allows you to define some rules for guessing the compile-command to use for a particular buffer. Like, if there's a makefile, use MAKE; otherwise, if the file is a .c file, use gcc; etc.

    This is nice if you don't want to insert comments into every file, or if you have a myriad of different kinds of files and projects that you work on.

ps: the reason your simple setq isn't working, I'd guess, is that you are not evaluating it in the buffer that is being edited. Probably you want to put that into your personal xxxx-mode-hook-fn, where xxx is the mode of the file you are editing.

Community
  • 1
  • 1
Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • Hmm, not sure I like the first option, but you're right: Emacs seems not to evaluate the expression locally. I've posted the fix, that works for me, with a hook. – LazyCat Apr 10 '12 at 03:35
  • just FYY this response explains why this solution works: http://stackoverflow.com/a/12758033/54848 – elviejo79 Jan 29 '13 at 20:20