My First Program - Introduction
5 Nov 07, 5:02PM
My First Program - Introduction
The language C was developed in 1972 by Dennis Ritchie. During the late 1970's to 1980's the object-orientated extension to C was developed, which was cunningly called 'C++' (where in C '++' means plus one).
For the most part there is no reason to use pure C, though some low level devices (mainly where memory is a premium) are still developed in this language. However while C++ adds many great features, it is also completely backwardly compatible, so C should work in C++. As such we rarely make the distinction between C and C++ within CodeCogs. However it is important to note that C++ is much more mature and strictly developed, further more is it thread safe, which mean you can write programs that work in a multi-tasking (multi-processor) environment like Unix, Windows XP or OSX.
In C, your first program might be:
In C++, your first program might be:
Ok, so what are all the bits of this program:
#include <stdio.h> int main() { printf("Hello world!!\n"); return 0; }This program will also work perfectly well in a C++ compiler. However many developers prefer to use a slightly more complex method for displaying information through the use of C++ stream, i.e.
In C++, your first program might be:
#include <iostream> int main() { std::cout << "Hello world!!" << std::endl; return 0; }
Ok, so what are all the bits of this program:
- The first line that you typically see at the beginning of any C/C++ function is a
#include
<..> statement. What this does is load the file found in square brackets and substitute it into that part of your code. In effect#include
give you access to previously written code, which avoids you having to write it all your self (a very long an laborious task even for the above simple program). You can often spot if a function is written for C++, if you see#include's
without a '.h' extension, i.e.
#include <iostream> // C++ with no .h #include <stdio.h> // C with a .h extension
- The next piece of code, "int main()" is the main entry point, where you program is going to start. The main function is always the start regardless of what language or platform you are using.
Compiling
We'll only show you how to do this using GNU C++ compiler, since its the most widely available. First save the above program (either the C or C++ version) as something with the
.cpp extension, e.g. myfirst
.cpp
Open up a console window and type:
g++ myfirst.cpp -o myfirstThe option '-o' tells gnu g++ what name to give the executable.