Writing and Compiling C programs on Linux
By Tony Lawrence2005-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.cThat's all good, and it works, but all those gcc's would get annoying real fast. This is where we use "make".
#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
$ cat MakefileYou need TABS after each ":" and before the gcc's on the lines that follow
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
each "rule". Basically, a makefile says "to make x, you need these files, and you run this command
target : TAB files neededLeave out tabs and make will complain:
TAB command needed
Makefile:5: *** missing separator. StopBut we got the tabs right, so now we can do "make hello" and it works:
$ make helloYou 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.
gcc -c hello.c
gcc -c pi.c
gcc -lm -o hello hello.o pi.o
$ ./hello
pi = 3.14159
$
Tutorial Pages:
» Writing and Compiling C programs on Linux
» Basic C Programming
» Hello World
» Compiling
» Make Files
© Copyright 2005 A.P. Lawrence
| 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 |
