Getting started with C in Linux

Downloading and installing the compiler

First, check to see if your computer already has XCode installed. Open up a terminal and type

gcc -v

If you see a message like

-bash: gcc: command not found

then you will need to install a compiler. Consult your distribution's documentation (or ask me) how to get gcc up and running. Otherwise, you will see some output like this (this output is from my Mac, yours will look different -- the important thing is that the command runs).

Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~105/src/configure --disable-checking
--enable-werror --prefix=/usr --mandir=/share/man
--program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib
--build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10-
--host=x86_64-apple-darwin10 --target=i686-apple-darwin10
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)

Installing a text editor

There are many text editors available for most distributions, but gedit is a nice simple one. Other than that, there are the two old standbys, vi (vim) and Emacs.

Testing out your installation

Create a folder for your programs in your home directory. ~/ccode/example, for example. Use your text editor to create a file called hello.c containing the following:

#include <stdio.h>

int main(int argc, char** argv) {
  printf("Hello, world!\n");
  return 0;


Now it's time to compile your program. Open up a terminal and type in (substituting whatever path you chose to put the source file in):

cd ~/ccode/example
gcc -o hello hello.c

You should get the output

Hello, world!

If so, you have successfully compiled your first program!

Using make to automate compiles

"Make" is a handy utility that recompiles your programs for you by detecting when the source code is more recent than the executable. We will test it by trying to get it to recompile your hello file, changing the source code, and recompiling again. We'll learn more about how to use make in class soon.

In the same directory as hello.c, use your text editor to create a file called makefile (no .c or .txt extension), containing:

hello: hello.c
	gcc -O3 -Wall -o $@ $^

The space at the start of the second line above is a tab character, not 8 spaces (you can enter a tab by hitting the tab key). Note that make won't work unless you indent certain lines with tabs!

If you go to the MINGW prompt, and type


you should see a message like

make: `hello' is up to date.

Now change hello.c to print something else (maybe "Hello, world, again!") and save the file. Go back to the MINGW shell and type


once more. It will print the line

gcc -O3 -Wall -o hello hello.c

indicating that it has recompiled your program for you.

Back to E15 home page