Home > Articles > Programming > C/C++

Compiling and Running Your First C Program

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

This chapter is from the book

This chapter introduces the basics of C programming in an easy-to-follow format, and includes some exercises you can try on your own to get you started.

In this chapter, you are introduced to the C language so that you can see what programming in C is all about. What better way to gain an appreciation for this language than by taking a look at an actual program written in C?

To begin with, you'll choose a rather simple example—a program that displays the phrase "Programming is fun." in your window. Program 3.1 shows a C program to accomplish this task.

Program 3.1 Writing Your First C Program

#include <stdio.h>

int main (void)
{
   printf ("Programming is fun.\n");

   return 0;
}

In the C programming language, lowercase and uppercase letters are distinct. In addition, in C, it does not matter where on the line you begin typing—you can begin typing your statement at any position on the line. This fact can be used to your advantage in developing programs that are easier to read. Tab characters are often used by programmers as a convenient way to indent lines.

Compiling Your Program

Returning to your first C program, you first need to type it into a file. Any text editor can be used for this purpose. Unix users often use an editor such as vi or emacs.

Most C compilers recognize filenames that end in the two characters "." and "c" as C programs. So, assume you type Program 3.1 into a file called prog1.c. Next, you need to compile the program.

Using the GNU C compiler, this can be as simple as issuing the gcc command at the terminal followed by the filename, like this:

$ gcc prog1.c
$

If you're using the standard Unix C compiler, the command is cc instead of gcc. Here, the text you typed is entered in bold. The dollar sign is your command prompt if you're compiling your C program from the command line. Your actual command prompt might be some characters other than the dollar sign.

If you make any mistakes keying in your program, the compiler lists them after you enter the gcc command, typically identifying the line numbers from your program that contain the errors. If, instead, another command prompt appears, as is shown in the preceding example, no errors were found in your program.

When the compiler compiles and links your program, it creates an executable version of your program. Using the GNU or standard C compiler, this program is called a.out by default. Under Windows, it is often called a.exe instead.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus