Cover: C Programming For Dummies, 2nd Edition by Dan Gookin

Title Page

C Programming For Dummies®

To view this book's Cheat Sheet, simply go to www.dummies.com and search for “C Programming For Dummies Cheat Sheet” in the Search box.

Introduction

When I was in school, I'd open a new math textbook and look in the back, marveling at the problems. Someday, I thought, I would understand all this nonsense.

You should do that with this book right now: Open it up to one of the final chapters. Look over the C programming code and think to yourself, “Someday soon, this will all make perfect sense to me.”

Say “Hello, world” to C Programming For Dummies, 2nd Edition, the book that sets you on the path to become a computer programmer. Once despised vermin, banished to basement server rooms and suffering from a lack of personal hygiene, programmers are now valued and contributing members of society. Some are billionaires. And they all started their careers by learning to program.

The C language lets you master a number of electronic gizmos. You can craft your own programs, dictating your every whim and desire to computers, tablets, and cell phones. The electronics dutifully obey. Given the information offered in this book, you can pass that programming class, impress your friends, be admired by Hollywood, or even start your own software company. Truly, learning to program is a worthy investment of your time.

This book helps make learning how to program understandable and enjoyable. You don’t need any programming experience — you don’t even need to buy new software. You just need the desire to program in C and the ability to have fun while doing so.

Why the C Language?

An argument surfaces every few years that learning C is a road to nowhere. Newer, better programming languages exist, and it’s far better to learn them than to waste time learning C.

Poppycock.

C continues to dominate the charts for best and most useful programming languages, often beating out the newer languages the cool programmers use. Further, C is like the Latin of computer languages: Just about every Johnny-come-lately programming language uses C syntax. C keywords and even certain functions find their way into other popular languages, from C++ to Java to Python to whatever the latest, trendy language might be.

My point is that once you learn C programming, all those other programming languages come easy. In fact, many of the books that teach those other languages often assume that you know a little C before you start out. This assumption is frustrating for a beginner — but not when you already know C.

So ignore the lofty pundits and know-it-all poohbahs. C is still relevant. Programming for microcontrollers, operating systems, and major software packages is still done using good ol’ C. You are not wasting your time.

The C Programming For Dummies Approach

As a programmer, I’ve toiled through many programming books. I know what I really don’t like to see, and, lamentably, I see it often — that is, where the author writes pages-long code or boasts about what he knows, impressing his fellow nerds and not really teaching anything. Too much of this type of training exists, which is probably why you’ve picked up this book.

My approach here is simple: Short programs. To-the-point demonstrations. Lots of examples. Plenty of exercises.

The best way to learn something is by doing it. Each concept presented in this book is coupled with sample code. The listings are short enough that you can quickly type them in — and I recommend that you do so. You can then build and run the code to see how things work. This immediate feedback is not only gratifying, it’s also a marvelous learning tool.

Sample programs are followed by exercises you can try on your own, testing your skills and expanding your knowledge. Suggested answers to the exercises and all the source code can be found on this book’s companion website:

https://c-for-dummies.com/cprog

How This Book Works

This book teaches the C programming language. It starts out by assuming that you know little to nothing about programming, and it finishes by covering some of the more advanced C operations.

To program in C, you need a computer. This book makes no assumptions about the computer you select: It can be a Windows PC, a Macintosh, or a Linux system. You can choose to use an integrated development environment (IDE) such as Code::Blocks, or you can compile and run the sample programs at a command prompt.

This book also wastes no time, getting you started immediately in Chapter 1. Nothing is introduced without a full explanation first. Due to the nature of programming, I’ve made a few exceptions; they’re carefully noted in the text. Otherwise, the book flows from front to back, which is how best to read this book.

C language keywords and functions are shown in italic text, as in printf() and break. Some keywords, such as for and if, may make the sentence read in a goofy way, which is why those words are shown in italic.

Filenames and variable names are shown in monofont type, such as program.exe and loop.

If you need to type something, that text is shown in bold. For example, “Type the blorfus command” means that you should type blorfus at the keyboard. You're directed when to press the Enter key, if at all.

When working numbered steps, text to type appears in regular (roman) type:

  1. Type exit and press the Enter key.

You type the word exit and then press the Enter key.

Program samples are shown as snippets on the page, similar to this one:

if( i == 1)
printf("eye won");

You don’t need to type an example unless you’re directed to do so.

Full program listings are shown and numbered in each chapter; for example:

LISTING 1-1 The Code::Blocks Skeleton

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("Hello world!\n");
return(0);
}

Because of this book’s margins, text in a listing may occasionally wrap, extending from one line to the next. You do not need to split up your code in a similar manner, and I remind you whenever such a thing occurs.

The listings in this book don’t contain line numbers, but your text editor might. This book references the sample code listings by using the line numbers, which you can also use in your editor to examine the code.

Exercises are numbered by chapter and then sequentially. So the third exercise in Chapter 13 is Exercise 13-3. You’re directed in the text to work an exercise. Here’s an example:

Exercise 1-1: Type the source code from Listing 1-1 into your editor. Save it under the filename ex0101.c. Build and run.

Answers for all exercises can be found on the web:

https://c-for-dummies.com/cprog

Go to this web page if you want to copy-and-paste the source code as well.

Icons Used in This Book

Remember This icon flags information worthy enough to remember. Though I recommend remembering as much as you can, these icons flag the stuff you just can’t forget.

Tip A tip is a suggestion, a special trick, or something super fancy to help you out.

Warning This icon marks something you need to avoid. It’s advice that could also be flagged with a Tip or Remember icon but has dire consequences if ignored.

Technical stuff Face it: All of programming is technical. I reserve the use of this icon for extra-technical tidbits, asides, and anecdotes. Call it “nerd stuff.”

Parting Thoughts

I enjoy programming. It’s a hobby, and I find it incredibly relaxing, frustrating, and rewarding. I assume that you share these feelings, though you may also be a struggling student or someone who wants a career. Regardless, enjoy programming. If you can imagine the program you want to write on a screen, you can make it happen. It may not happen as fast as you like, but it can happen.

Please work the exercises in this book. Try some on your own, variations on a theme. Continue working at problems until you solve them. The amazing thing about programming is that no single, absolutely correct way to do something exists. Anytime you try, you’re learning.

If possible, find a programming friend who can help you. Don’t make them do the work or explain how things run, but rely on them as a resource. Programming can be a solo thing, but it’s good to occasionally commiserate with others who also program in C — or in any language.

This book has a few companion websites. The primary one is found here:

https://c-for-dummies.com/cprog

You can also check out my C programming blog, which is updated every Saturday with new lessons and offers a monthly Exercise challenge:

https://c-for-dummies.com/blog

The publisher also features a companion website, which I’m obliged to mention here, though it’s not updated as frequently as my own site. Visit www.dummies.com and type C programming into the search box to find this book’s support page and other goodies.

For more help, or just to say hi, you can send me email at

dan@c-for-dummies.com

I’m happy to hear from you, though I won’t write code for you. I also cannot explain university assignments. (I don’t do B-trees. No one does.) And if you have any questions specific to this book — especially any errors or typos — feel free to pass them along.

Enjoy your C programming!

Part 1

The ABs of C

IN THIS PART …

  • Get started with C coding
  • Work through your very first program
  • Learn how programming works
  • Discover the parts of the C language
  • Craft a basic C skeleton

Chapter 1

A Quick Start for the Impatient

IN THIS CHAPTER

check Reviewing software requirements

check Programming at the command prompt

check Using an IDE

check Creating a command prompt program

check Working in Code::Blocks

check Compiling a program

You’re most likely eager to get started programming in C. I shan’t waste your time.

Tip If you already have a compiler or an IDE set up and are ready to go, skip to Chapter 2.

What You Need to Program

The two most important things you need to begin your programming adventure are

  • A computer
  • Access to the Internet

The computer is your primary tool for writing and compiling code. Yes, even if you’re writing a game for the Xbox, you need a computer to be able to code. The computer can be a PC or a Macintosh. The PC can run Windows or Linux.

Internet access is necessary to obtain the programming software. You need a text editor to write the code and a compiler to translate the code into a program. The compiler generally comes with other tools you need, such as a linker and a debugger. All these tools are found at no cost on the Internet.

The software tools offer two approaches to programming: command line and IDE.

If you want to learn C programming as I did back in the dark ages, you use a terminal window and traditional command-line tools: editor, compiler, and linker. The process is fast, but complicated because you’re using text mode commands. Still, it offers a spiritual connection with those who built the foundations upon which the computer industry roosts.

The most common way to craft code, however, is to obtain an integrated development environment — called an IDE by the cool kids. It combines all the tools you need for programming into one compact, terrifying, and intimidating unit.

Don’t freak! The terms compiler, linker, debugger, and terrifying are all defined in Chapter 2.

Command Prompt Programming

To re-create the environment where the C language was born, use a Unix or Linux terminal window running a shell program such as bash. This environment is available to all major computing platforms, and the programming tools used are reliable and well-documented. Programming at the command prompt earns you a nerd merit badge and the admiration of your peers.

For Windows 10, open the Microsoft Store app and install Ubuntu, a free Linux shell. Ensure that you follow the directions to install the Windows Subsystem for Linux, which is an extra step you’ll probably miss.

For Linux, you’re ready to go: Open a terminal window to access the shell.

For Mac OS X, use the Terminal app. I also recommend obtaining the Homebrew package manager. Visit https://brew.sh for directions. Homebrew allows you to install programming tools not available to OS X.

For an editor, you can use any text mode editor available at the command prompt, such as vi or emacs. You can also “mix it up” and use a window-based editor. I’m fond of using the Windows version of the VIM editor while I simultaneously work at the command prompt in an Ubuntu terminal window.

A C compiler comes native to a Unix/Linux command prompt. The standard version is cc or gcc, but I recommend that you use the shell’s package manager to acquire the LLVM clang compiler. In Ubuntu Linux for Windows 10, type this command to install clang:

sudo apt-get install clang

Type your account password to initiate the process. To verify the installation, type

clang --version

Various Linux distros offer similar package managers, which you can use to obtain an editor and the clang compiler.

  • The VIM editor can be obtained from vim.org.
  • Remember Your choice to use the command prompt means you’re taking on an extra layer of complexity when it comes to programming. I find it fast and enjoyable, but if you believe it to be too much, especially when first learning the C language, rely instead upon an IDE, as covered in the next section.

IDE Programming

Plenty of programming IDEs are available for your C coding pleasure. On the Mac, use Xcode, which you can install from the App Store. For Windows and Linux, I recommend obtaining the Code::Blocks IDE, which is found at codeblocks.org. You can choose any other IDE you prefer, but Code::Blocks for Windows is fairly stable and comes with everything you need — providing that you install the correct version.

Installing Code::Blocks

The Code::Blocks website will doubtless be altered over time, so follow these general steps to install the IDE and confirm that the C compiler is accessible:

  1. On the main Code::Blocks website page, click the Downloads link.
  2. Click the binary release link.

    The “binary release” means you’re installing a runnable program, not source code or something equally strange.

  3. Choose the proper installation program for your computer’s operating system.

    For Windows 10, I recommend that you choose the installation with the text mingw-setup appended. For example:

    codeblocks-20.03mingw-setup.exe

    The 20.03 part of the filename is the release number, which will change in the future. The mingw-setup choice means you're downloading both the IDE and the MinGW compiler.

    Tip For Linux, click the link to install the proper version for your distro, but keep in mind that Code::Blocks might be more easily acquired by using the Linux GUI package/software manager.

  4. Open the downloaded archive to extract the Code::Blocks IDE installer.

    In Windows, you see a User Account Control warning when you open the archive. Click Yes to proceed with installation.

  5. Run the installation program.

    Perform a default installation; you need not customize anything.

  6. Choose to run Code:Blocks: Click the Yes button.

    Code::Blocks appears, showing its splash screen. Don’t start coding now. Instead, confirm the compiler’s installation:

  7. Choose Settings, Compiler.

    The Compiler Settings dialog box appears.

  8. With Global Compiler Settings chosen on the left, click the Toolchain Executables tab on the right side of the dialog box.
  9. Ensure that the Compiler’s Installation Directory text box is filled.

    In a default confirmation, the following pathname is listed:

    C:\Program Files (x86)\CodeBlocks\MinGW

    If the text box is blank, use the Browse button (three dots to the right of the text box) to locate the MinGW installation directory.

  10. Confirm that gcc.exe is set in the Compiler text box.

    If not, click the Browse button (three dots) to locate the gcc.exe program, installed in the MinGW\bin directory by default.

  11. Close the Compiler Settings dialog box; click OK.

Installation is complete. I recommend you close the Code::Blocks window. Finish the installation program as well.

Touring the Code::Blocks workspace

Figure 1-1 illustrates the Code::Blocks workspace, which is the official name of the massive mosaic of windows and toolbars you see arranged on the screen.

Screenshot of a window displaying the Code::Blocks workspace, which is the official name of the massive mosaic of windows and toolbars arranged on the screen.

FIGURE 1-1: The Code::Blocks workspace.

On your computer, as well as in Figure 1-1, locate the following parts of the workspace:

Toolbars: These messy strips, adorned with various command buttons, cling to the top of the Code::Blocks window. The toolbars can be rearranged or hidden, so don't mess with them until you get comfy with the interface.

Management: The pane on the left side of the workspace features four tabs, though you may not see all four at one time. The window provides a handy oversight of your programming endeavors.

Status bar: At the bottom of the screen, you see information about the project, editor, and other activities that take place in Code::Blocks.

Editor: The big window in the center-right area of the screen is where you type code.

Logs: The bottom of the screen features a window with many, many tabs displaying various tidbits about the programming process. The tab used most often is named Build Log.

The View menu controls the visibility of every item displayed in the window. Choose the pane name, such as Manager, from the View menu to show or hide that item. Control toolbars by using the View, Toolbars submenu.

  • Tip Maximize the Code::Blocks program window so that it fills the screen. You need all that real estate.

  • In addition to color-coding your text, the Code::Blocks editor offers an autocomplete feature. Items that must be typed in pairs, such as quotes, parentheses, and so on, are generated automatically for you. Certain C language keywords and functions are presented automatically, along with hints for their arguments and options.
  • The editor features a tabbed interface, which lets you work on multiple source code files at one time.

Your First Program

The traditional first program written for any programming language is called Hello World. It’s boring, like all traditions.

Listing 1-1 shows the Hello World source code as presented in Code::Blocks. This code is generated by default whenever you start a new Code::Blocks project.

LISTING 1-1 The Code::Blocks Skeleton

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("Hello world!\n");
return 0;
}

The programming process works the same whether you use the command prompt or an IDE:

  1. Use an editor to write the source code.
  2. Compile and link the source code into a program.
  3. Run the program to see whether it works.

Chapter 2 goes over these steps in detail, but I assume you’re in a rush. The following sections cover the specifics for the command prompt and IDE environments.

Coding at the command prompt

Use your text editor to create a new file and type in the text presented in Listing 1-1. This code, like all source code in this book, is available on the companion website: https://c-for-dummies.com/cprog.

Save the source code file as ex0101.c. The filename must end in .c (“dot C”) to be recognized as a C source code file by the compiler.

Compile and link, or “build,” the source code into a program file in a Unix terminal window, such as the Ubuntu bash shell in Windows 10. Type the following command in the same folder/directory where the source code file is saved:

clang -Wall ex0101.c

The name of the compiler program is clang. The -Wall argument activates all warning messages. The final argument is the name of the source code file, ex0101.c, in this example.

Upon success, you see no output. If you see warnings or error messages, you probably mistyped the source code. Try again: re-edit and compile.

To run the program, type the default program filename a.out. In a terminal window, the program name must be prefixed by ./ (“dot slash”) to direct the command interpreter to look in the current directory:

./a.out

You see the message Hello, world! output in the terminal window. Now skim to Chapter 2 to discover what just happened.

Building a new Code::Blocks project

Two approaches can be used in Code::Blocks to build the sample code shown in this book: You can build a project for each exercise or you can use an empty file to write the code.

Create a project

For a project, follow these steps:

  1. Choose File, New, Project.
  2. Choose Console Application and then click the Go button.
  3. Select C as the programming language and then click the Next button.

    C is quite different from C++ — you can do things in one language that aren't allowed in the other.

  4. Type a project title.

    The code exercises in this book follow a naming pattern you can use for the project title: ex followed by a 2-digit chapter number and 2-digit sequential number. For the sample code presented in Listing 1-1, the project title is ex0101.

    When you set the project title, the project’s filename is automatically filled in.

  5. Click the … (Browse) button to the right of the text box titled Folder to Create Project In.

    I recommend that you create and use a special folder for all projects in this book. Once the location is set, you can skip this step in the future.

  6. Click the Next button.

    The next screen (the final one) allows you to select a compiler and choose whether to create Debug or Release versions of your code, or both.

    The compiler selection is fine; the GNU GCC Compiler (or whatever is shown in the window) is the one you want.

  7. Remove the check mark by Create Debug Configuration.

    You create this configuration only when you need to debug, or fix, a programming predicament that puzzles you. See Chapter 25.

  8. Click the Finish button.

Code::Blocks builds a skeleton of your project, which is the same code shown in Listing 1-1. Skim to the later section “Building and running.”

Create an empty file

A less complicated method for working with this book’s exercises is to type the source code into an empty project file. Obey these steps in the Code::Blocks IDE:

  1. Choose File, New, Empty File.
  2. Type the source code into the editor.

    You can also copy-and-paste the source code from the companion website into the editor. Refer to the introduction for details on the companion website.

    Tip If you’d prefer to see the editor color-code your text, save the file! Press Ctrl+S and choose the folder where you plan to keep all this book’s programming projects. Name the file according to this book’s convention: ex followed by a 2-digit chapter number and 2-digit project number. End the filename in .c (“dot C”) to identify it as a C source code file.

  3. Save the source code file.

    If the file is already saved, press Ctrl+S. Otherwise, follow the naming convention listed under Step 2.

After the empty file is created, you can build and run the program just as you would had you run through the bothersome technique of starting a Code::Blocks project.

Tip You can also open the source code file directly in Code::Blocks, if you’ve obtained it from the companion website: Use the Open command to open the file. At this point, you can build and run, modify the code, or do whatever your heart pleases.

Building and running

In Code::Blocks, the process of compiling and linking C language source code is accomplished in one step called Build.

Image of the Build button icon present on the toolbar that is clicked to build a project. To build the project, click the Build button on the toolbar, as shown in the margin and illustrated in Figure 1-1. Any compiler warnings or errors appear on the Build Log tab at the bottom of the window. For Listing 1-1, no warnings or errors should be generated, providing the code is input exactly.

Image of the Run button icon that is played to test-run a program. To test-run the program, click the Run button, shown in the margin and illustrated in Figure 1-1. Output appears in a terminal window, as shown in Figure 1-2.

Screenshot of a terminal window displaying the output of a program that has been test-run.

FIGURE 1-2: Program output.

Press the Enter key to close the output window. In Linux, you must type the exit command to close the window.

Image of the Build and Run button icon that is clicked when both build and run steps are combined. Both build and run steps are combined when you click the Build and Run button, shown in the margin.

When you’re done with a project, or even after you’ve changed a minor thing, save it. Save the source code file, but also save the project if one was created: Choose File, Save Everything to save both the source code and project files.

  • Commands for building and running the code are also found on the Build menu.
  • The keyboard shortcuts for Build, Run, and Build and Run are Ctrl+F9, Ctrl+F10, and F9, respectively. No need to memorize those shortcuts; they’re listed on the menu.
  • Technical Stuff The program output appears in the top part of the command prompt window (refer to Figure 1-2). The last two lines are generated by the IDE when the program is run. The text shows a value returned from the program to the operating system, a zero, and how long the program took to run (0.005 seconds).

Chapter 2

The Programming Thing

IN THIS CHAPTER

check Understanding programming history

check Reviewing the programming processes

check Creating source code

check Building a program

check Testing the final program

It’s called programming, though the cool kids know it as coding — the process whereby a human being writes information resembling cryptic English that is then somehow translated into directions for an electronic gizmo. In the end, this silent and solitary art grants individuals the power to control electronics. It’s a big deal. It’s the programming thing.

The History of Programming

Few books written about programming get away with not describing the thrill-a-minute drama of programming history. As a programmer myself, it’s difficult not to write about it, let alone contain my enthusiasm at cocktail parties. So consider this section optional reading, though a review of where programming has been and where it is today may help you better understand the art form.

In a nutshell, programming is the process of telling a gizmo what to do. That gizmo is hardware; the program is software.

Reviewing early programming history

The first known machine to be programmed was Charles Babbage’s analytical engine, back in 1822. The programming took place by physically changing the values represented by a column of gears. The engine computed the result of some dull, complex mathematical equation.

In the 1940s, early electronic computers were programmed in a similar manner to Babbage’s analytical engine. A major difference was that, rather than rearrange physical gears, instructions were hard-wired directly into electric circuitry. “Programming” pretty much meant “rewiring.”

Over time, the rewiring job was replaced by rows of switches. Computer instructions were input by throwing switches in a certain way.

Professor John von Neumann pioneered the modern method of computer programming in the 1950s. He introduced decision making into the process, where computers could make if-then choices. Professor von Neumann also developed the concept of the repeating loop and the subroutine.

It was Admiral Grace Hopper who developed the compiler, or a program that creates other programs. Her compiler would take words and phrases in English and translate them into computer code. Thus, the programming language was born.

The first significant programming language was FORTRAN, born in the 1950s. Its name came from formula translator. Other programming languages of the period were COBOL, Algol, Pascal, and BASIC.

Remember Regardless of the form, whether it’s rewiring circuits, flipping switches, or writing a programming language, the result is the same: telling hardware to do something.

Introducing the C language

The C language was developed in 1972 at AT&T Bell Labs by Dennis Ritchie. It combined features from the B and BCPL programming languages but also mixed in a bit of the Pascal language. Mr. Ritchie, along with Brian Kernighan, used C to create the Unix operating system. A C compiler has been part of that operating system ever since.

In the early 1980s, Bjarne Stoustroup used C as the basis of the object-oriented C++ programming language. The ++ (plus-plus) part of the name is kind of an in-joke, which you’ll understand better after reading Chapter 11. Mr. Stoustroup intended C++ to be the successor to C. In many ways it is, yet C remains one of the most popular programming languages.

  • The B programming language, upon which C is based, was named after the B in Bell Labs.
  • BCPL stands for Basic Combined Programming Language.
  • The C++ programming language is quite similar to C, but it’s not merely an extension or an add-on. It’s easier to learn C++ when you know C, but it’s not easy to switch between the languages.
  • A D programming language exists. Developed in the early 2000s, it’s not as popular today as other current languages, such as Python and Java.
  • Unfortunately, I have no idea how to pronounce “Bjarne Stoustroup.”

The Programming Process

No matter which language you use, certain procedures are common to the programming process. In this manner, learning to program is like learning to cook: You must take things in a certain order, whether the result is crème brûlée or a smoldering pile of egg glop.

Understanding programming

The goal of programming is to create a program. The language is C, and the tools are the editor, compiler, and linker — or an IDE, which combines everything. The result is a program that directs the hardware to do something. That hardware can be a computer, tablet, phone, microcontroller, or whatever.

Step-by-step, the programming process works like this:

  1. Write the source code.
  2. Compile and link, or build, the source code into a program.
  3. Run and test the program.

A human (you) writes source code. The source code is built into a program in two steps: compiling it into object code and then linking the object code with C libraries to build the program. Finally, that program is run.

The reality goes more like this:

  1. Write the source code.
  2. Compile the source code into object code.
  3. Fix warnings and repeat Steps 1 and 2.
  4. Link the object code with libraries to build the program.
  5. Fix errors and repeat Steps 1 through 4.
  6. Run and test the program.
  7. Fix bugs by repeating the entire process.

    Or, more frequently, the program runs fine but you want to add a feature or refine an element. Then you repeat everything.

Hopefully, Steps 3, 5, and 7 don’t happen often. Still, you do a lot of fixing in the programming cycle.

The good news is that the compiler dutifully reports the errors and even shows you where they are. That’s better than tracking down a bug in miles of wires back in the old ENIAC days.

  • Despite having “build” as a single step, the compiler still creates object code, and a linker links the object code into a program. If you goof up royally, linking doesn’t even happen and you must fix the compiler warnings before taking the next step.
  • One of my professional programmer friends said that the art form should be called debugging, not programming.
  • Technical Stuff Legend has it that the first computer bug was a moth that Grace Hopper found in the wiring of an early computer. There’s some doubt about this legend, considering that the word bug has been used since Shakespeare’s time to describe something quirky or odd.

Writing source code

Source code represents the part of the process that contains the programming language itself. You use a text editor to write a source code file.

In this book, source code is shown in program listings, such as the example in Listing 2-1.

LISTING 2-1 Standard “Hello World” Program

#include <stdio.h>

int main()
{
puts("Greetings, human.");
return 0;
}

Line numbers are not shown in this book’s listings. They aren’t part of the code, and showing them here can be confusing. The text editor may display line numbers for reference purposes.

In this book, you’re directed to type the source code from a listing as part of an exercise. For example:

Exercise 2-1: Start a new project in Code::Blocks named ex0201. Or use your text editor to create the source code file ex0201.c for compiling and linking at the command prompt.

Do it: Obey Exercise 2-1, either in Code::Blocks, at the command prompt in a terminal window, or in another C language IDE, such as Xcode on the Mac.

  1. Write the source code in the editor, copying it from Listing 2-1.

    Alternatively, you can copy-and-paste the code from the companion website or use the listing's source code file, downloaded from the website. Refer to this book’s introduction for details.

    If you’re creating a Code::Blocks project, erase the skeleton that’s provided and replace it with the code shown in Listing 2-1.

  2. Save the source code file.

There. You’ve just completed the first step in the programming process — writing source code. The next section continues your journey with the compiler.

  • Remember All C source code files end with the .c (“dot-see”) filename extension.

  • In Windows, I recommend that you set the folder display options so that filename extensions appear.
  • C++ source code files have the extension .cpp (“dot-see-pee-pee”). I shall refrain from writing a puerile joke here.
  • Technical Stuff Source code files follow the same naming conventions as any file on a computer. Traditionally, a small program has the same name (but not extension) as the final program. If your program is named puzzle, the source code is most likely named puzzle.c.

Compiling and linking

Traditionally, the compiler reads text from a source code file and translates that text — a programming language — into something called object code. The linker then creates the final program. It links the object code file with C language libraries to create a program. All this happens exactly as written — unless a warning or an error crops up along the way.

You can compile and link separately in an IDE or at the command prompt. Fortunately, modern compilers combine both steps in a process called build.

Image of the Build toolbar button icon that is clicked to build a project in Code::Blocks. To build the project from Listing 2-1 in Code::Blocks, click the Build toolbar button (shown in the margin) or choose Build ⇒ Build from the menu. Any errors present themselves on the Build Log tab as well as on the Build Messages tab.

To build the program at the command prompt, type this line in the same directory (folder) as the source code file (ex0201.c):

clang -c -Wall ex0201.c

First comes the compiler name, clang, followed by the -Wall switch to report all warnings. The final argument is the source code filename. Upon success, you see no feedback; otherwise, warnings and error messages spill on the screen like fruit from an upturned apple cart.

(Running the program file is covered in the next section.)

  • The object code file has the same name as the source code file, but ends in .o (“dot-o,” “little o”). If the source code file is named ex0201.c the object code file is named ex0201.o. The modern build process deletes this file unless you specifically direct the compiler to generate and retain the object code file.
  • As the compiler translates your C code into object code, it checks for common mistakes, missing items, and other issues. If anything is awry, the compiler displays a list of warnings. To fix them, you re-edit the source code and attempt to compile once again.
  • The linker brings in the C language library, which is how the final program is built. The libraries contain the actual instructions that tell the computer (or whatever device) what to do. Those instructions are executed based on the shorthand directions found in the object code.
  • Any mistakes found by the linker are called errors. When errors occur, a program isn't created; errors are fatal.
  • Some C programs link in several libraries, depending on what the program does. In addition to the standard C library, you can link libraries for working with graphics, networking, sound, and so on. As you learn more about programming, you’ll discover how to choose and link in various libraries. Chapter 24 offers the details.

Running and testing

Run the program.

Image of the Run toolbar button icon that is clicked to test-run a project in Code::Blocks. In Code::Blocks, choose Build ⇒   Run or click the Run toolbar button, shown in the margin.

At the command prompt, type the program name prefixed by the current directory:

./a.out

The name a.out is the default C program filename. You can reset this name by specifying the -o (“little o”) switch followed by the desired output filename when building. For example:

clang -Wall ex0201.c -o ex0201

The preceding command uses the source code in ex0201.c to build a program named ex0201. It must be run at the command prompt in the same manner as a.out:

./ex0201

The program runs, outputting text, which appears on the next line after you type the program name:

Greetings, human.

In Code::Blocks, output appears in a terminal window. Press the Enter key to close the window. For Code::Blocks in Linux, type the exit command to close the output terminal window.

A program like ex0201 doesn't require much testing to ensure that it works. As your programming skills mature, testing, rewriting, compiling, and debugging become a standard part of the process. Don’t be discouraged; this is how all programmers learn the craft.

  • The mechanics of running a program are carried out by the device’s operating system: The operating system loads the program into memory, where the processor or CPU executes the code. This is a loose description of how a program works.
  • Technical Stuff In Windows, the program name ends with the exe (for executable) extension, as in ex0201.exe. In Mac OS X, Linux, and Unix, the program name has no extension: ex0201. Further, in those operating systems, the file’s permissions are set for the file to run as an executable.