Programming Tutorial - Part 5

Getting some output

Ok - it's time to print things!  Yay!  Along the way we'll learn a little about errors and libraries too.  Magic!

Now - as we said earlier C and C++ don't really include many functions at all.  Printing text to the screen is one of the things that C/C++ don't do for us, so we'll need a *library*.  A library is a collection of functions (often, but not always written in C/C++) that we can borrow.  On PCs a library is provided as a .lib file - you can get 1,000's of lib files from the internet or write your own containing all your favourite things.  Pretty much all versions of C for all computers include with them a standard library of useful things - printing, file access, maths functions etc - and the PC is no exception.  The library with all the great things in it is called "libcmt.lib" (which is short for "Library for C - Multi Threaded" but don't worry about that at the moment) but luckily for us it's been automatically added to our project when we created it in Visual Studio - usually everyone needs it so it's the default.

 Adding some code

 Ok - in "main" we'll add some code to print things.  Just before the "return 0;" line, add:

printf("The total is: %d\n", total);

We'll worry about the syntax later, but let's Compile!  Hit F7.

Oh.

In the output window you should see something like:

1>Compiling...
1>main.cpp
1>c:\documents and settings\chris\my documents\visual studio 2008\projects\
project1\fred\fred\main.cpp(30) : error C3861: 'printf': identifier not found
1>Build log was saved at "file://c:\Documents and Settings\Chris\My Documents\
Visual Studio 2008\Projects\Project1\Fred\Fred\Debug\BuildLog.htm"
1>Fred - 1 error(s), 0 warning(s)

 What went wrong?  Well, if you double-click on the error line (the one ending with "'printf': identifier not found") we can see what it's unhappy about.  The new printf line has generated an "identifier not found" error whilst compiling.  This is because we didn't tell the compiler anything about our new function - it doesn't know if we've got the syntax right or not - maybe we made an error!  Maybe the parameters were totally rubbish!  So, how can you tell the compiler about a function without having to write it all out (afterall, that's what the library is for)?  The answer is a *declaration*.

 Definitions and declarations

These two words are often confused in C, so I'll take a bit of time to explain them.  A definition of something is where you actually say what the thing is in detail.  In our program we have 2 function definitions - one for SquareIt and one for main.  We say what the functions are and define them in detail - we've given them a name and a body.  On the other hand, a declaration is where you only say what a function is going to be like.  You don't actually specify how the function behaves.  So - how do you declare a function?  Well, you just tell the compiler what the function accepts as input, what it's called and what it returns - this is enough for the compiler to work out how to use the function without giving the body of code itself.

For example, we've already had the definition of the function SquareIt.  What would its declaration be? Well, it's just the first header line of the function:

int SquareIt(int value);

  This is enough for the compiler to allow us to use the function SquareIt - it doesn't need to know what happens inside.  Of course, when the compiler's done its job and the linker comes to join everything together, there'd better be a function body called "SquareIt" somewhere - otherwise your program will be incomplete!

   How can this be useful?  Well, it means that you don't need to have all your functions in one file.  You can just have the declarations of functions you'll be needing from other places so you can break your program into sections.  It also means that if you want to use someone else's library of functions they only need to give you the declarations of what they've written - then you can use those and the compiler will know what you're talking about.  For example, if you write a great library for calculating grocery prices, I can use them like this:

float PriceOfRice(float weightInPounds);
float PriceOfTreacle(float weightInPounds);
int main() 
{
	float cost;
	cost =  PriceOfRice(0.5) + PriceOfTreacle(0.5);

Great!  But... how do I know these declarations?  Well, it's sucha useful thing to do that C users tend to bundle all their declarations into files called header files.   There's no strict definition of what should be in a header file - they could contain any C you want - but traditionally (and in order to make them useful) they only contain declarations.  In this case we might have:

  File GroceryPrices.h (this is the header for your library GroceryPrices.lib):

float PriceOfRice(float weightInPounds);
float PriceOfTreacle(float weightInPounds);
 
  File Main.cpp (this is the main file of my application):
 
#include "GroceryPrices.h"
int main()
{
	float cost;
	cost =  PriceOfRice(0.5) + PriceOfTreacle(0.5);

The line "#include ..." isn't a statement so it doesn't finish with a ;.  It's a line that tells the compiler to nip to another file and start reading that one instead.   As far as the compiler is concerned this version of my program will look identical to the one up above without the include - 2 declarations and then the definition of the function 'main' - but for us it's a lot easier to use.  You give me your GroceryPrices.h and your GroceryPrices.lib and I can use them together to calculate prices.

 Finally - let's print something!

 Ok - so to get our program happy with "printf" we just need to know where the declaration of the function "printf" is.  Well, it's stored in "stdio.h" (short for Standard Input Output - not Studio as I always read it...).  So, change our program by adding this at the top:

#include "stdio.h"

 Hit F7 and... It's happy!  Hopefully everything compiled that time.  Also, notice that it linked too - this is because your call to printf managed to get joined to the library function printf successfully.  Remember that we got the library for free when we made our project.  To run your proud masterpiece, press Ctrl + F5 (Run).  Hopefully a black DOS box thing should pop up saying:

The total is: 385
Press any key to continue . . .

 

The "Press any key" line is added by the command console to let you read your hard-earned output.  Well done! 

 

 

Digg! Reddit! Del.icio.us! Mixx! Google! Live! Facebook! StumbleUpon! TwitThis Joomla Free PHP
Add this page to your social bookmarking websites
Last Updated on Monday, 08 September 2008 16:58