2

I'm currently learning C with a book that has many small code examples that the reader is supposed to write, run and experiment with. I'm using Emacs as my primary tool for everything that has to do with writing, especially LaTeX and Org-Mode to date. I'm already using Emacs for my C-stuff but there are always ways to optimize. Specifically i'm searching for a way to have a key-binding, that saves, compiles and runs the file that is my current buffer!

Chances are, that there are some included files that also need to be considered in the build process.

All IDEs that i know of have a "compile and run" button and are not using any Makefiles and such (which would be overkill in my situation).

Is there a way or a package to achieve my expected behavior or would i be better off with using Qt-Creator or Visual Studio? I've done a quick google search but have found nothing satisfying yet. Would be thankful if someone could help me out because manually saving, compiling and calling the binary can get tedious if you're writing 20-30 smaller programs a day

2

1 Answer 1

3

Since you are using Org-mode and all you want (according to your post), is to evaluate small C code examples, I'd use ob-C and just evaluate everything using org-babel.

This is not an answer on how to compile and run C code directly, but a convenient alternative using Org.

Fire up an org file and try the following (taken from this awesome blog post):

#+HEADERS: :includes <math.h> :flags -lm 
#+HEADERS: :var x=1.0 :var y=4.0 :var z=10.0
#+BEGIN_SRC C :exports both
double pi = 4*atan(1);
double r, theta, phi;
r = sqrt(x*x+y*y+z*z);
theta = acos(z/r) * 180.0/pi;
phi = atan2(y,x) * 180.0/pi;
printf("%f %f %f", r, theta, phi);
#+END_SRC

Note that if you need multiple includes, you have to pass them in a list, as in #+BEGIN_SRC C :includes '(<math.h> <time.h>). Also note that ob-c will default to wrapping your code within a main block. If you don't want that, then pass :main no to inhibit wrapping. See more info here.

3
  • Thank you very much! That indeed was helpful! But to be honest, i'm really looking for a way that deals with .c or .h-Files and that don't depend on org-mode!
    – Tim Hilt
    Commented Apr 10, 2018 at 20:07
  • Can’t really help there. Hope somebody else tips in, but I‘m sure there are guides out there. Search for Tuhdo‘s c guides
    – Daniel
    Commented Apr 10, 2018 at 20:56
  • I actually don't understand why this behaviour isn't requested more commonly! Thanks for the tip, i will definitely investigate!
    – Tim Hilt
    Commented Apr 10, 2018 at 21:50

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.