This tutorial is for those of you who don't want to deal with the menus of an IDE or the need to build a multi-story project for every little program. The following gives you an introduction to writing, compiling, and linking programs from the command line using the gcc C compiler. Pretty much everything contained herein also works for the g++, the C++ compiler.
First, write a C program using your favorite editor. Decent GUI editors include TextWrangler (on macs only), JEdit (cross-platform). More traditional text editors include emacs (now available as a standard mac application in addition to commandline), vi (text only command line editor), and nano (another text only command line editor). You may also want to learn/use an IDE such as XCode (Macs), Eclipse, Sublime, Visual Studio (Windows)
If, for example, you wanted to write your program using emacs, you would type
emacs myfile.c &
which should open up a new window with the emacs editor in it. If you are new to emacs, go through the built-in tutorial. If you're in a hurry, the things you need to know are:
- cntl-x cntl-f to open a file
- cntl-x cntl-s to save the currently active file
- cntl-x cntl-c to save and exit the program
Download or copy the linked C program, which reads in all the numbers on the command line and finds the square root of the sum of squares of the numbers. The program also shows you how to grab numbers or arguments from the command line, include standard C header files, and print stuff.
A C program has to be compiled before you can run it. The most commonly used compiler is gcc (Gnu C compiler). To compile a C program using the command line, you can use the following.
gcc -o myprog myfile.c -lm
Your terminal might look like:
The way to parse the above is that gcc is the command, -o is a flag that says the next argument is what the executable should be called. The file to be compiled is next (myfile.c) and the last argument -lm is the -l flag, which links in a library, and m is the math library. So the command says to compile myfile.c, link in the math library, and make the executable myprog.
If you have code in multiple C files, then you can list all of the files to compile together on the command line. If you need to link in other libraries you can use additional -l arguments.