January 22, 2010

Your First C Program

Before going through this tutorial you need to make sure that you’ve installed XCode first.

Make a folder on your desktop called MyFirstCProgram. Use your favorite text editor. Copy and paste the following into a new file and save this file in MyFirstCProgram as hello.c.

#include "stdio.h"
 
int main(int argc, char** argv)
{
   printf("Hello, world!\n");
}

Open up Terminal.app. This can be found in the Utilities directory of your Applications directory (/Applications/Utilities to be exact). You will be dropped into your home directory.

terminal

Change directories to the location where you put your file. You can do this by typing something like the following followed by the return key.

cd /Users/davidnolen/Desktop/MyFirstCProgram/

You can also type cd, drag the folder that contains the file into Terminal.app and then press enter.

terminal2

You should now be in the same directory. You can check by typing:

pwd

That’s short for print working directory. Command line programs tend to have terse names to save on typing. Compile your file with the following line of code.

gcc hello.c -o hello -Wall

Notice you get some warnings, it’s OK, your program compiled anyway. You just called a command line program called gcc with some arguments. If you done some work with Arduino, you might know that Arduino also uses gcc with some extensions for the AVR chip. You must find out what these arguments stand for by the following class by going over the assigned readings. You can execute you new program with the following line:

./hello

Congrats you’ve written your first C program. I’m sure you have a lot of questions, some of which will be answered by a close reading of the assigned text. Come back next week with a boatload of questions. If any part of the tutorial does not seem to work, please let notify me immediately.

Leave a Reply