Hello World!


Let's start off with an example
#include /* some comment */ void main( ) { printf("Hello World!\n"); }

Here's how to compile and run it in UNIX:

UNIX prompt >> ls
Hello.c

UNIX prompt >> gcc Hello.c
UNIX prompt >> ls
Hello.c a.out

UNIX prompt >> a.out
Hello World!

UNIX prompt >>

gcc invokes the GCC compiler. The result of invoking the compiler on a C file is the creation of an executable, which by default is called "a.out".

If you want your executable to be called something else (other than a.out), you can specify that during compilation, using the -o flag:

 

UNIX prompt >> ls
Hello.c

UNIX prompt >> gcc -o say_hello Hello.c
UNIX prompt >> ls
Hello.c say_hello

UNIX prompt >> say_hello
Hello World!

UNIX prompt >>

 

Explaining Hello.c line-by-line:
Note -- All C files must end in ".c"


#include
The above line should be included at the beginning of almost every C program. It contains (among other things) the printf output routine that is used in the program.
/* some comment */
This is a comment line. You can also write comments as a block with '/*' at the beginning and '*/' in the end. For example, /* This is a comment block. This block consists of several lines. I can write anything in this block except another comment -- that would cause compilation errors! */
main( )
This informs the system that the name of the program is main. Every program written in C begins execution with the main routine. The parenthesis following main indicate that main is a function. (Refer to the section on functions). Also, every function body must be enclosed within curly braces { }
printf("Hello World!\n");
This line prints out the string "Hello World!" when the program is executed. Note the "\n" at the end of the string. "\n" is referred to as the "newline character". Anything after the newline character would be printed on a separate line.

Important Note:

Every line in C must end with a semicolon (;)
Unlike MATLAB where semicolon is used to suppress the output of that line, a missing semicolon at the end of the line would result in a compilation error – usually a "Parse Error" in UNIX.

Hint
The first thing you should check for in case you get a "Parse Error" during compilation, is a missing semicolon.