Running your first C program
Your hello1.c
program has been successfully compiled, and you now have an a.out
file in the same directory. It's time to run it! Let's get started:
- In a Terminal, command-line, or console window (depending on your OS), navigate to the directory that holds
a.out
. - At the command prompt, usually indicated by a
>
character in the first column, enter./a.out
. - You should see
Hello, world!
. - If you see that, we can now verify the output of your program.
- Note that the command prompt,
$
, is not on the same line asHello, world!
. This means you correctly entered\n
in the output stream. If not, you need to re-edithello1.c
and make sure\n
occurs immediately preceding the second"
, recompile it, and reruna.out
. - If
Hello, world!
is on a line by itself with a command prompt before and after it – woo-hoo! You did it!
If everything works as it should, you should see the following output in your Terminal:
Figure 1.1 – A successful compilation and execution of hello1.c
In the screenshot of our Terminal session, >
is the prompt the Terminal gives to indicate that it is ready to take input from us. After the first prompt, we have entered cc hello1.c
followed by <return>
. The fact that the very next thing we see is another prompt means that the compilation was successful, and we can now run the compiled program. We then enter a.out
followed by <return>
to execute hello1.c
. We should see our desired message, Hello, world!
, followed by a prompt awaiting Figure 1.1 – further input.
If the compiler spews out any error messages, read what the compiler is telling you and try to understand what error it is telling you to fix. Always focus on the very first error message, to begin with; later error messages are usually the result of the very first error. Then, go back to the editing phase and examine where your entered program is different from what has been shown here. The two must match exactly. Then, come back to this phase; hopefully, your program will compile successfully (that is, there will be no error messages).
It's always important to remember to do a little dance, and make a little joy, get down tonight! when you've successfully completed something. Programming can be very frustrating, so remembering to celebrate even your small successes will make your life a little bit more joyful through all the frustration. Too many programmers forget this incremental and regular step of celebrating with joy!
As we progress through this book, we'll add more compiler options to the cc
command to make our life easier.
Tip
If you skipped over the Understanding the program development cycle section of this chapter, now would be a good time to read it before moving on.