Monday, July 11, 2011

Coding Lessons: simple C programs

Perhaps I'm stretching things a little far now introducing a third set of lessons, it will inevitably mean that all lessons run a little slower, I hope that I'm not stretching myself too thin. I think that at this level at least the lessons are so simple that they can be written up fairly quickly.

I just hope I'm not proved wrong, after all, I'm trying to give lessons on Electronics, Crafting and coding now, as well as going to work, living a life, and making things.

But this is the third lesson type, and covers the third area of interest that this blog is interested in, coding -writing programs.

My feeling is that even if you don't have time to make furniture (write up coming soon) restore furniture (write up coming soon), make home audio equipment (write up coming soon), make tools (write up(s) coming soon), anyway, if you don't have the time, or you don't have the space, or you don't have the money for these things, then by reading this I'm guessing that you have a computer, and you can at least make some virtual things.

I'm not going to be writing a tutorial on how to write games in C++, I may write some tutorials on using shell scripts in both Windows and Linux, but for now I'm writing tutorials on ordinary (ANSI) C.

In the end these lessons in C will be geared towards programming micro-controllers. (Microchip PIC devices).
But you have to walk before you can run.

I've said before on a forum that I frequent, those that say "Help, I need to learn C++ so that I can write a game" are pretty much destined to never learn either C++ or how to make games.
I honestly think that the best approach to learning is to break things up into small manageable chunks and get your head down and study and learn.

The first thing that you're going to need is a compiler, When I first started using C I learned using Visual Studio 6, that tool is good, and the newer versions of visual studio are in my opinion even better. (Visual Studio is an IDE -Integrated Development Environment, it contains an editor, and a compiler and debugger all in one package, whilst this is all very well, it's overkill for beginer situations.)

However, I won't be using Visual Studio, because it's a cost option, and it's not available on Linux/Unix/Mac, instead I'll be using a free C compiler.

I'm using Tiny C compiler, which I found by just searching for "free C compiler" -we'll get onto how to use it later.

Next you're going to need something to actually write the code in.
I'm going to be using notepad, but feel free to use jedit, turbopad, emacs, pico, vi, the msdos edit program, you own IDE or your own favourite plain text editor. note I said plain text editor. Something like MS office will not work, because it saves a document with formatting information, you need just a plain text file.

Setting up
I prefer to keep everything nice and organised. You don't have to use the same system as me, indeed I'm on windows, so if you're on Linux or Mac, you'll have to adapt the instructions to suit, I have a C and D drive, you might only have one, or you might have more! again, use your own brain and decide how you want to do things.

First, get the free C compiler that was linked above, and unzip the file to your D drive, this will create a folder called "tcc" inside this tcc folder is the compiler.
you can run the compiler from this folder without any further changes.

from the command prompt:
c:\>d:\tcc\tcc.exe "D:\coding\Lesson1\helloworld.c"

This creates a file called hello world.exe at the C drive.

however, to make things a little easier for yourself, you should really just add d:\tcc to the "path" environmental variable, (I won't cover how to do that here, improve your google fu by finding it our for yourself).

Now you'll be able to just run tcc from any folder without having to enter the path.

I've also created a folder on my D drive called coding.
inside that is a folder called Lesson1

Hello World
Perhaps the simplest of programs is the ubiquitous hello world program, using this will enable you to actually create some source code, compile that to an executable, and actually run a program.

To start with, load your editor (notepad).

This is where you start to need to know something about the way in which C works, and the way in which compilers work.

You might like to put a comment into your program.

Comments are used to put information into the source code for a program, that might be a copyright notice, or instructions for how to use. It might be notes to yourself on how and why you've done things. there are many discussions on what are good an bad comments. but you choose for yourself what you'd like your comments to be.
The compiler will ignore anything marked as a comment. (it won't compile it). this lets you remove stuff from a program by commenting it out whilst you're testing.

in C comment blocks are started with a start then a forward slash */
comment blocks are ended by a forward slash, followed by a star /*

/* my
comments */

So anyway, the next line might be:

/* Hello World
A simple console program, that outputs hello world to the console, then exits.
Version: 1.0
Created: 08/07/2011*/

These comments are fairly useful, they tell you what the program does (without you having to read through the source code), they tell you the version of the program -admittedly not so important in this simple program, but when you've got a program that's taken many weeks to do and you've perhaps got a few different backups saved. or you know that it was working last week and can't see what you changed etc, it's nice to have some version control!
It also tells you the date that you created it. -which can help when you;re documenting your project later.

In C, something with a hash/pound in front of it is an instruction for the compiler.
The top line of the code (after your comment) in your file will be #include < stdio.h >
the #include command tells to compiler that you want to link to another file, you want that code included in your program.

stdio.h is a header file that contains all the code needed to be able to accept inputs from the user, and output to the screen. Using these pre-made headers saves you having to write all the functions for outputting text.

Next you need to set up the main part of your program, the bit where things actually happen.

To do this you write int main()

Some books will tell you to write void main(void), or void main() this declares the return type, in ANSI C void is a valid return type, and your compiler will compile it... but for reasons that will come up in later tutorials, declare the main runtime as an int.

In programming there are routings, and sub routines, and loops and such. you have just started the main routine.

Everything inside the main routing needs to be encased in curly brackets { } to show that it's included inside of this routine. (if that doesn't make sense keep reading, it will at the end.)

So at this point, you've got your header file that contains all the code needed to interact with the display.
You've written some helpful comments that'll remind you what you wanted to do.
You've started your main routine.

Now you want to make it do something, in this case, the Hello world program, all we want the program to do is print hello world to the screen, and then exit.

To make the program print "Hello World" to the screen, you use the command:
then you open some brackets to say what will be printed, (
what you want to say goes inside quote marks "
printf("Hello World")

Then in C all the lines of code that are like this need to be ended with a semi colon ;

printf("Hello World");

Then you need to close that curly bracket to mark the end of the main routine.

The complete program is now:

/* Hello World
A simple console program, that outputs hello world to the console, then exits.
Version: 1.0
Created: 08/07/2011*/

#include <stdio .h>

int main()
printf("hello world");

OK, so now you need to save that file.

Click on file and click on save.
make the save location your project folder (D:\coding\lesson1).
and call the file "helloworld.c"

To do this, on the save screen, at the bottom change the file type from "Save as type: Text documents (*.txt)"
to "Save as type: All files (*.*)"

The enter the file name as "helloworld.c" (yes, do actually put the quotation marks into the file name box).

On Linux or Macs this steps might be different, indeed different editors on windows might be different, the important thing is that your file has the extension ".c" if it has the extension ".txt", or ".c.txt" then the compiler won't like it.

So now you've got your source file written, and your source file saved.

Now you need to use the command prompt, (in windows click on start, then click run, then type "cmd").

You need to navigate to your project directory,
cd \
cd coding
cd lesson1
If you type dir at this point you should see helloworld.c is contained in this folder.

now you can either type
>d:\tcc\tcc.exe helloworld.c

or, if you added the tcc compiler directory to your system path earlier you can just type
>tcc helloworld.c
(if you're not using this compiler you may need to look at the manual for your own compiler for instructions on how to run it).

You should now see (if you type dir) that a new file called helloworld.exe has been created.

Still at the command prompt, type helloworld.exe, you should see that your program runs, displays the text "Hello World" and the exits, leaving you back at the command prompt.

You can of course change the message from Hello World to anything that you like.

That was a lot of work for displaying two words wasn't it!
but that's because this was a complete beginner lesson and I've tried to explain things as simply as possible! (that and the fact that as I said earlier, sometimes making stuff is hard, and requires learning!).

If there is anything that's confusing, or you feel could be written better, or requires elaboration, leave a note in the comments and I'll see about making some changes.

No comments: