2

I want to bind to a key a compile-and-run function to be able to compile my C++ single file programs and run them into a term/shell so I could give my variables values whenever I use cin in my programs.

For example, in my Neovim config, I had this line:

autocmd FileType cpp  nnoremap <F8> :w <CR> :vsp <CR> <C-w>l :term g++ % -o %< && ./%< <CR> i

I want to have something similar in Emacs. In Emacs, this line will be looking like so:

(define-key c++-mode-map (kbd "<f8>") #'compileandrun)

But I have no clue how the compileandrun function will look.

edit 1: Here is a function I have tried

(defun compileandrun()
  (interactive)
  (compile (concat "g++ "  (file-name-nondirectory (buffer-file-name)) " -o " (file-name-sans-extension   (file-name-nondirectory 
           (buffer-file-name)))))
   (term  (concat "./" (file-name-sans-extension
           (file-name-nondirectory (buffer-file-name))))))

it only compiles the program but it dosen't run it .

user26482
  • 31
  • 5
  • Please put your answer in its own post rather than include it in the question. It's fine to self-answer. – Dan Jan 07 '20 at 02:04

2 Answers2

2

compile uses the shell. You can chain program execution with && like g++ test.cc -o test && ./test. With the last command ./test is executed if compilation with g++ succeeds.

I'll modify your command accordingly:

(defun compileandrun()
  (interactive)
  (let* ((src (file-name-nondirectory (buffer-file-name)))
         (exe (file-name-sans-extension src)))
    (compile (concat "g++ " src " -o " exe " && ./" exe))))
Tobias
  • 33,167
  • 1
  • 37
  • 77
1

Here is the final elisp function that works. It automatically switches to the window and move the cursor to the bottom .

(defun compileandrun()
  (interactive)
  (save-buffer)
  (compile (concat "g++ "  (file-name-nondirectory (buffer-file-name)) " -o " (file-name-sans-extension   (file-name-nondirectory (buffer-file-name))) " && ./" (file-name-sans-extension  (file-name-nondirectory (buffer-file-name)))) t )
(other-window 1)
(end-of-buffer)
) 
(add-hook 'c++-mode-hook
          (lambda () (local-set-key (kbd "<f8>") #'compileandrun)))

If you have any improvments let me know .

user26482
  • 31
  • 5