How to send the content of an emacs buffer to gcc without writing to disk

emacsgcc

It's common for me to run a throwaway piece of code I'm not particularly interested in saving on my disk, so I'm often working inside emacs in a buffer not attached to any file in my system.

When working with interpreted (I'm a little reluctant to use this term) languages like Python, Scheme or Lua, each respective major mode (the common ones) offer ways of running the REPL/interpreter inside the editor and executing the content of a buffer directly. (Generally with a function called send-buffer or something like that).

However when working with C, I cannot find a similar functionality. I find myself forced to save the file to disk, in order to give gcc a filename as argument.

Is there a way to send the content of an emacs buffer to gcc without writing the file to disk?

Best Answer

Use C-x h (mark-whole-buffer), then'M-| (shell-command-on-region), then use @Kotte's suggestion above to run gcc -x c -o tmp_prog - && tmp_prog

Or here's an elisp function that does it:

(defun compile-and-run-buffer()
  "Compiles the code in the buffer using gcc, run the exe and remove it."
  (interactive)
  (shell-command-on-region
   (point-min)
   (point-max)
   "gcc -x c -o emacs_tmp - && ./emacs_tmp && rm emacs_tmp"))