tags:

views:

92

answers:

4

Hi,

I want this function to compile the contents of the current buffer(a C file) and show the output(a.out) if the compilation succeeded

(defun c-shell-compile ()
  (interactive)
  (save-buffer)
  (if (equal (shell-command (concat "gcc " (buffer-file-name))) 
             "(Shell command succeeded with no output)")
      (shell-command "./a.out")
    ;;Else show the errors        
    ))

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

But it does not seem to be working, if the compilation succeeds it just says "(Shell command succeeded with no output)" without showing the output.

Answers or directions very much appreciated.

+4  A: 

The result of shell-command is the status. So don't compare it to a string but to 0

(defun c-shell-compile ()
   (interactive)
   (save-buffer)
   (when (= 0 (shell-command (concat "gcc " (buffer-file-name))))
         (shell-command "./a.out")))
AProgrammer
Thank you, it worked! , and now C is as interactive as python(for small files atleast) ;)
jimbo
Btw , had to add a ) after (buffer-file-name)
jimbo
@jimbo, thanks for the notice, I fixed the code.
AProgrammer
A: 

This version uses 'compile (as mentioned in a comment above this will let you jump to error messages etc.)

(defun c-compile ()
  (interactive)
  (compile (concat "gcc " (file-name-nondirectory (buffer-file-name))
                   " && ./a.out")))
Damyan
A: 

Like most elisp code, you can extend the compilation process using hooks:

This is the way you should go. Sooner or later you will want to check compilation errors, save dependent buffers, ... and don't wan't to reinvent the wheel:

(add-hook 'compilation-finish-functions 
      (lambda (buffer desc)
        (when (string-equal desc "finished\n")
        (shell-command "./a.out"))))
Jürgen Hötzel
+2  A: 

And yet another solution:

M-x compile RET gdb <filename> && a.out

You can get the default compilation command to be that by setting the variable compile-command either as a file variable, directory variable, in a mode hook, or manually. This works well if a.out doesn't require user input from stdin.

Trey Jackson