Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Writing and Compiling C programs on Linux

By Tony Lawrence
2005-04-22


Make Files

With just this much knowledge, you can actually write C programs. You don't need make files (though make files are of course very useful for bigger programs). If the program needs no special compiler flags, "make" is smart enough to know what to do all by itself, as we saw earlier. As you write bigger programs, you'll find that "gcc -Wall" and "lclint" will help you spot your mistakes. But let's "make" something a bit more complicated. It's two files, and we'll be using a new compiler switch:

$ cat pi.c

#include <math.h>

mypi()
{
printf("pi = %.5f\n", 4 * atan(1.0));
}

$ cat hello.c
#include <stdio.h>
main ()
{
mypi();
}

$ gcc -c pi.c
$ gcc -c hello.c
$ gcc -lm -o hello hello.o pi.o
$ ./hello
pi = 3.14159
That's all good, and it works, but all those gcc's would get annoying real fast. This is where we use "make".

$ cat Makefile

pi.o: pi.c
gcc -c pi.c

hello.o: hello.c
gcc -c hello.c

hello: hello.o pi.o
gcc -lm -o hello hello.o pi.o
You need TABS after each ":" and before the gcc's on the lines that follow
each "rule". Basically, a makefile says "to make x, you need these files, and you run this command

target : TAB files needed

TAB command needed
Leave out tabs and make will complain:

Makefile:5: *** missing separator.  Stop
But we got the tabs right, so now we can do "make hello" and it works:

$ make hello

gcc -c hello.c
gcc -c pi.c
gcc -lm -o hello hello.o pi.o
$ ./hello
pi = 3.14159
$
You are going to make more mistakes. If you are like most of us, pointers and indirect pointers (char *this, char **that) are going to confuse you, and you'll misuse them. Lint and gcc -Wall will help you somewhat, but you'll still probably screw up. You'll forget that you are referencing something on a long overwritten stack. You'll blithely dereference past the end of an array and your programs will crash as they get killed off for trying to change somebody else's memory space. Don't feel badly, other people have stumbled and lurched down the same path before you. Buy a beginner's C book, and have at it.

Tutorial Pages:
» Writing and Compiling C programs on Linux
» Basic C Programming
» Hello World
» Compiling
» Make Files


© Copyright 2005 A.P. Lawrence


 | Bookmark
Related Tutorials:
» How to Install PHP 5 on Linux
» How to Install Apache 2 on Linux
» How to Install MySQL 5.0 on Linux
» SMB Caching
» Mound --Bind
» Tar Wild Card Interpretation