A Simple C Program

 < Day Day Up > 

This section provides a simple example of how to create an executable program for Linux by using gcc. One of the shortest programs you can write in C for Linux is the quintessential "hello, world" program (popularized by Brian W. Kernighan and Dennis M. Ritchie in their 1978 book The C Programming Language).

To get started, type in the following text, using your favorite Linux text editor:

 main(){     printf("hello, world.\n");  } 

When you are finished, save the file as hello.c, and then compile the program by using the gcc compiler system, like this:

 $ gcc  o hello hello.c 

This command line creates an executable program named hello, using the file hello.c as input. You can then run the program like this:

 $ ./hello hello, world. 

The C program contains only one function, named main(). The gcc command line specifies the name of the output program (using the -o option) and the input source file, hello.c. Note that in order to run the new hello command, you must specify it explicitly, using the period and forward-slash characters, as the program is not installed in a normal command directory (such as /usr/bin or /usr/local/bin).

NOTE

You can build large programs in C. C programs can be broken into any number of files, as long as no single function spans more than one file. To compile a program, you compile each source file into an intermediate object before you link all the objects into a single executable. The -c flag tells the compiler to stop at that stage. During the link stage, all the object files should be listed on the command line. Object files are identified by the .o suffix.


     < Day Day Up > 


    Red Hat Fedora 4 Unleashed
    Red Hat Fedora 4 Unleashed
    ISBN: 0672327929
    EAN: 2147483647
    Year: 2006
    Pages: 361

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net