C Programming in Linux

Writing a Program in Emacs

  1. Open a console window (aka shell window, aka terminal emulation window).

  2. Open a .c file in emacs (or xemacs):
    emacs hello_linux_world.c &

  3. Learn how to use emacs by reading the emacs tutorial:
    C-h, t (press Control, press 'h', release control and 'h', press 't')

  4. Write a simple program:
    #include <stdio.h>

    int main(void) {
        printf("Hello world\n");
        return 0;
    }

  5. Save the file
    C-x, s

Compiling the Program Using gcc

To compile your program enter in a console window:
gcc -Wall -O2 -o hello_world hello_world.c

gcc is the name of the compiler. -Wall is a flag telling gcc to turn on all warning flags. -O2 turns on all optimizations except loop unrolling and function inlining. -o hello_world sets the output file (ie. the executable file) to hello_world. If you don't use the -o flag the default outputfile a.out is used. The last argument (hello_world.c) is a list of input files (ie. source files and object files).

Two other useful flags are:

If you want to learn more about gcc you can read the gcc info pages:

  1. Open emacs.

  2. Start info
    C-h, i

  3. Choose the gcc menu item
    m, gcc

Some info commands are:
p: previous
n: next
u: up
m: menu
d: go to directory node
f: follow cross reference
s: search
q: quit

To learn more about info read the info info page :-)

Running the Program

When you have compiled the program you can run it by entering in the console window:
./hello_world

./ means that the executable file is in the current directory (dot).

Man pages

Not all programs have info pages, some (especially older) programs only have man pages. To use man, enter in a console window:
man "program name"

For example: man grep.

There are also man pages for all functions in the C standard library. To learn about printf enter:
man printf

Makefile

To avoid having to type "gcc -Wall -O2..." every time you can use a Makefile. Click here for an example file. To use it enter "make" or "make hello" in a console window. Look at the output and see if you can understand what happens.

Tip: Use make hello_linux_world.s to make an assembly file.

For more information, read the info pages.

Compiling Assembly Programs

The easiest way to compile an assembly file is to use gcc. Just add the assembly file to the input file list. For example: gcc -Wall -O2 -o mixed c_file.c assembly_file.s.

You can also use gas (the gnu assembler).

Debugging

Use KDbg. From the KDbg homepage: "KDbg is a graphical user interface to gdb, the GNU debugger. It provides an intuitive interface for setting breakpoints, inspecting variables, and stepping through code. KDbg requires KDE, the K Desktop Environment, but you can of course debug any program."


Lars Ailo Bongo, University of Tromsų, Spring 2002.