Creating a self compiling C/C++ source code
Here’s a nice trick I use from time to time. I’m just putting it out there so I can better remember it and so that everyone can learn from it.
Before we start with the tip proper, let’s just put that in context.
Let’s pretend for a second that you’re coding in C or C++ and you want to try out something you’ve found while browsing a documentation or stumbled upon in a gist. You want to be able to do that quickly just to test stuff out.
What would you do? Load an IDE? Create a entire Visual Studio Solution just to try out a few lines of code?
What I would do in that situation is quickly create a source file and add line indicating how this file should be compiled at the beggining. Making this source file executable will allow you to “run” the source code in order to compile and run the output. For instance, given a C source file named
test.c, you can do the following:
Add the following line to the beginning of the file:
//usr/bin/gcc text.c -o test;./test;exit
Make the source code executable by running the following command as root:
chmod +x text.c
Once this is done, you can run the source code to compile and run the program:
You’re done. That’s a lesser known trick that I like a lot. It would be a good idea to leave these lines in as you share single file projects, demos and tests.