Wednesday, October 31, 2012

CPP 1 - Program Structure and Compilation

Previous | C++ Home | Next


In order to program in C++ you will need:
  1. Computer.
  2. Linux or Windows Operating System.
  3. C++ compiler.
If you use linux the compiler is already available for you. In case you use windows operating system, you will need to download some IDE with C++ compiler. You can use one for free at: http://www.codeblocks.org/

The best way to learn how to write programs is ... to actually start writing them. Unlike some other, also  cool programming languages, such as  python which is are called 'interpreted' language, C++ is a bit more difficult to start with. Every time we have a problem to solve using C++, we will need to carry out the following steps:
  1. Writing a code in a text editor (or IDE).
  2. Compile it (if there is problem with our syntax, the compiler will tell us about it).
  3. Correct any problems found by the compiler (missing semicolon, brace, etc.).
  4. Run the code to test it.
Later, we may find some problems that the compiler will not find (called them bugs). They are more difficult to find, but in our course we should not have to many problems of this sort.

C++ is very fussy about details (syntax), so I advise that you type each code I present here watching every character (comma, semicolon, lef/right brace etc) as you do so.  

NOTE
Do NOT copy and paste the code ever. You develop your skills by typing the code as well.

NOTE
You probably do not know what compilation is and there will be many things that will baffle you in the beginning. Do not worry about it now. Just take those things for granted.  Explanations to those bits will come later. Now, it is all about repeating the process and having some fun with it From now on, you are the boss.

Here is your initial code structure we will use starting every program (well, sometimes we will add some more stuff, but the below will always be present). 


Pic. 1.1 - C++ Program Structure

Code Structure:


#inlcude <iostream>

using namespace std;

int main() {

return 0;
}


If you have carefuly typed in the code above into your editor or software development kit, and saved it as ex001.cpp, now compile it. If you did well, the compiler will not show any error. If you use linux box you can use the following command (do not type in the '$' sign):


$ g++ -o ex1 ex001.cpp

If you use Microsoft Windows and codeblocks IDE, just open a new project, type the code in and save it. Then click the icon in the menu that has a green arrow similar to the one used on DVDs ;). If you see no errors in the bottom of the page we're good.