I am having this in my init file to reset the compile command in the C mode, but when I run the C-c C-c inside C mode I will get the old command make ... meaning my new command hasn't been set. Why? Here is the code:

(add-hook 'c-mode-hook
      (lambda ()
        (set 'compile-command
         (let* ((file (file-name-nondirectory buffer-file-name))
            (fname (file-name-sans-extension file)))
           (format "gcc -c -g -Wall -Wextra -Werror -std=c99 -pedantic -o %s.o %s"
               fname fname))))
      0 t)

(add-hook 'c-mode-hook
      (lambda ()
        (local-set-key (kbd "C-c C-c") #'compile)))

1 Answer 1


When you call (add-hook …  0 t) the t means to add the hook locally to the current buffer. When you load a C file, it creates a new buffer, and that hook isn't active in the new buffer.

I believe you can solve the problem by removing the 0 t from the first add-hook call. That ways it will add the hook globally, and it will run in new buffers.

  • But it still will be active only in C mode right?
    – Student
    Commented Aug 9, 2021 at 14:31
  • 2
    Yes, c-mode-hook should run for all C mode buffers. However, compile-command by default is global to all buffers. You probably want to change this from (set 'compile-command … to (set (make-local-variable 'compile-command) … like the example from the help page for compile-command. That way it will set the value only in the current buffer and not affect any other buffers, and each buffer can have its own compile-command.
    – amitp
    Commented Aug 10, 2021 at 19:14

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.