![]() |
- 1 -
At the command line, pick a directory to save you program to, and enter:
vi firstprog.c
Note:
All C source code files must have a .c file extension.
- 2 -
Enter the following program, then save and exit Vi:
#include <stdio.h> int main() { int n; for (n = 0; n < 7; n++) printf ("Hello, World!\n"); return 0; }
- 3 -
Enter:
gcc -o myprog firstprog.c
...to, using the GNU C Compiler (gcc), compile and output (-o) an executable file, called myprog, from the source code, firstprog.c.
- 4 -
To run the program, enter:
./myprog
Here's an explanation of the above program:
| 1 | #include <stdio.h> | During compilation, include the header file stdio.h, located in the /usr/include directory, and required by the printf function call in line 6, so the program knows what printf does. Functions allow a program to be broken down into pieces, and called when required at points in a program. For details on stdio.h, enter: man stdio |
| 2 | int main() | Begin the main() function, a special function indicating where to begin the program when it's run. |
| 3 | { | The beginning brace, indicating the content's of the main() function featured in lines 4-7. |
| 4 | int n; | Declare the integer (whole-number) variable n. A variable being a placeholder for data. For example, n could store 42, or -253, but not x or 5.1. (For the latter two, you would use char n and float n, respectively.) |
| 5 | for (n = 0; n < 7; n++) | Begin a loop, causing the content of the loop (line 6) to repeat while the variable n is less-than 7 (n < 7). n begins at 0 (n = 0), and after each iteration of the loop (i.e. after line 6), is incremented by 1 (n++). |
| 6 | printf ("Hello, World!\n"); | Print to screen the string "Hello, World!". The \n (newline character) part causes the next thing to be printed to screen to start on a new line. |
| 7 | return 0; | Exit the main() function (and therefor the program), returning a 0, indicating success to the operating system. The presence of this line is why the int part features in line 2. |
| 8 | } | The ending brace, indicating where the function, in this case main(), ends. |
| Copyright © 1998-2002 Linuxdot.org. |
| Linux ® is a registered trademark of Linus Torvalds. |