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()
  (compile (concat "g++ "  (file-name-nondirectory (buffer-file-name)) " -o " (file-name-sans-extension   (file-name-nondirectory 
   (term  (concat "./" (file-name-sans-extension
           (file-name-nondirectory (buffer-file-name))))))

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

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

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()
  (let* ((src (file-name-nondirectory (buffer-file-name)))
         (exe (file-name-sans-extension src)))
    (compile (concat "g++ " src " -o " exe " && ./" exe))))
  • You will need to use let* form here because 'src' variable is used inside the 'exe' binding; otherwise you will get error about void variable for 'src' – crajun Jan 22 at 16:36
  • @crajun Thanks, corrected. – Tobias Jan 23 at 4:10

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

(defun compileandrun()
  (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)
(add-hook 'c++-mode-hook
          (lambda () (local-set-key (kbd "<f8>") #'compileandrun)))

If you have any improvments let me know .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.