Home‎ > ‎CS 11M‎ > ‎

Arduino vs. Standard C++

Questions, Answers and Review

  • Questions from last class?
  • Questions about homework?

Arduino C/C++ vs. Standard C++

C++ Program Structure

  • In Arduino C++, programs have two required functions:
    void setup() {
      // put your setup code here, to run once:
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
    }
    
  • Standard C++ programs are also structured into functions
  • However, a standard C++ program has a single required function main(), defined like this:
    int main() {
        // program statements go here
        return 0;
    }
    
  • Programs begin executing at the first line of the main() function
  • Within a function, code runs from top to bottom, left to right in a continuous sequence, just like with the Arduino
  • To the main() function shown above we could add another statement like:
    int main() {
        cout << "Hello, World!\n";
        return 0;
    }
    
  • First the computer prints "Hello, World!\n"
  • Then the computer exits the program with a return statement in main()
  • When the program execution completes, control returns to the operating system (OS)

Check Yourself

  1. True or false: every C++ program has at least one function.
  2. Standard C++ program starts executing in the ________ function.
  3. True or false: the default behavior for program statements within a function is to execute sequentially.

Libraries and Namespaces

  • Like the Arduino, standard C++ uses libraries of predefined code
  • Standard C++ has a number of standard libraries, also like the Arduino
  • However, the Arduino IDE automatically includes some libraries
  • In standard C++, the programmer must manually include every library required for the program
  • Thus the most basic standard C++ code usually includes the first two of the following statements

Example C++ Code with a Library

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
}

Libraries and include Directives

  • To use a library, we add the include directive to our programs
    #include <libraryName>
  • Technically, #include is called a "preprocessor directive"
  • It executes before compiling, and copies a library into our program file
  • Most standard C++ programs begin with a declaration like:
    #include <iostream>
  • The iostream library is for console input and output (I/O)
  • This library allows us to use the word cout for sending data to a terminal screen
  • Other libraries exist for math, strings and more
  • Some compilers are picky about spaces in include directives
    • Do not put spaces before or after the # sign
    • Do not put spaces inside the angle brackets

Namespaces

  • Namespace: a set of name definitions where all the names are unique
  • As part of programming, we assign names to parts of the code like variables, functions and classes
  • We can only use a name once within a namespace
  • All standard libraries put their definition in the namespace: std
  • To use these standard names, we add the directive:
    using namespace std;
  • Thus, most of our programs will begin with two statements:
    #include <iostream>
    using namespace std;
    

Check Yourself

  1. A library is a collection of ________ code.
  2. We use libraries in our programs to ________.
  3. We tell the compiler to use the library named iostream by writing ________.
  4. To tell the compiler to use the standard namespace write ________.

Developing a Standard C++ Program

  • Standard C++ is a list of instructions just like the Arduino
  • We type the C++ code into a text file known as a source code file

    source code: instructions for a computer written in a programming language

  • The following example shows the source code for a very simple C++ program

Example C++ Standard Source Code

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
}

Entering and Saving Source Code

  • We can use almost any text editor to enter and save C++ source code
  • We use TextPad in the classroom and you can download it for use at home
  • We enter our source code into TextPad and save the file as: hello.cpp
  • Make sure you save the source code file using the extension: .cpp
  • All C++ source code files must have the correct extension or the compiler program will not work

Check Yourself

  1. True or false: source code is text written in a programming language.
  2. Our standard C++ source code files have the file extension ________.
  3. True or false: To write C++ source code you should use a text editor or IDE, not a word processor like Word.

Terminal (Console) Window

  • The most basic way to compile and run a C++ program is to use the command line
  • The command line interface is available using a terminal (console) window

Opening a Terminal Window

  • Windows: search for "cygwin" and select the Cygwin Terminal
  • OS X: search for "terminal" and click the Terminal application
  • Linux: search for "terminal" and select the Terminal application (more...)

Using a Terminal Window

  • To use a terminal window, we type commands at a command prompt
    $ g++
    
    • $ is the command prompt (do not type this)
    • g++ is the command we type
  • After typing a command, we press the Enter key
  • If our g++ installation was successful, we will see a message like:
    $ g++
    g++: fatal error: no input files
    compilation terminated.
    

Exiting a Terminal Window

  • At the command prompt, type exit

Stopping a Program

  • Stop any program running in a terminal by typing Ctrl-C (pressing the Ctrl and C keys at the same time)

Navigating Directories

  • To get around in a file system, we need to navigate its directory tree
  • Everything in a file system is stored in a computer file
  • Files are grouped together into computer folders, also called directories
  • Folders are organized in a hierarchical structure starting at the root folder directory tree structure
  • A path is the directories we must go through to get to the file we want
  • We can see this structure in the Windows explorer:
    • Right-click on the Start button
    • Select Open Windows Explorer from the list
  • The left-hand side shows the directory structure
  • The Address bar shows the path (if you click within it)
  • At the command line, we only work with the path
  • We must understand folders and paths to work with our files

Navigation Using the Command Line

  • When the command line starts, we are located in our home directory
    • The home directory depends on your computer
  • We can check the current folder path using pwd (print working directory)
    pwd
  • We can list the files in the current folder using ls
    ls
  • We can change directory on our computer using the cd command in various ways
  • To change to our home folder: cd ~
    cd ~
  • To change up one folder level: cd ..
    cd ..
  • To change to a lower subfolder level: cd folderName
    cd Desktop
  • To change to the root of the file system: cd /
    cd /
  • To change to any arbitrary folder: cd path
    cd /cygdrive/c/Users/Student/Desktop

    Notice that Cygwin calls the C: drive: /cygdrive/c/

Check Yourself

  1. After entering a command, always press the special key named ________.
  2. To display the current directory in the terminal window, enter the command ________.
  3. To list all the files in the current directory, enter the command ________.
  4. To navigate to your home directory, enter the command ________.
  5. To navigate to a subdirectory named Desktop, enter the command ________.

More Information

Compiling and Running Programs Using g++

  • Now that we can use the command line in a terminal window, we will look at how to compile programs
  • The command for compiling a C++ program is:
    g++ -o programName sourceFile.cpp
    
  • For example, to compile our hello.cpp file we would type:
    g++ -o hello hello.cpp
    
  • This command produces the file hello.exe (just hello on Mac/Linux) from the source file hello.cpp
  • When we type the compiling command, a whole series of steps take place
  • These steps are shown in the following diagram
  • These steps are also followed when compiling on the Arduino

Compilation Process

Compilation process

Running a Compiled Program

  • To run a compiled program type ./ and its name after the command prompt
    ./programName
  • The operating system runs the file named programName.exe
  • Note that an .exe suffix is automatically appended
  • Thus, we do not need to type the .exe part of the program name

Example C++ Standard Source Code

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
}

Step-By-Step Instructions for Compiling and Running hello.cpp

  1. Start Cygwin if using Windows or Terminal if using Linux or the Mac.

    Select the Cygwin Terminal from the Start menu. In the classroom, Cygwin is located in the CS & CIS submenu.

  2. Save your hello.cpp source-code file using a text editor into your home folder. On Windows, this will be the Cygwin home folder:
    C:\Cygwin\home\yourHomeDirectory
  3. Type the compile command:
    g++ -o hello hello.cpp

    If no errors occur, the compiler creates the file: hello.exe. You can see this new file by typing: ls

  4. At the command prompt type:
    ./hello

    You should see the program display a message.

Check Yourself

  1. The recommended place to save C++ source code files when compiling from the command line, assuming it is a Windows machine, is to the ________ folder.
  2. What command do you type at the command line to compile a program named "foo.cpp"
  3. What command do you type at the command line to run the program you compiled in the previous question?

More Information

Exercise 1: Compiling a Program (6m)

In this exercise we explore how to compile and run C++ programs in the classroom.

Specifications

  1. Start TextPad and enter this code:
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    }
    
  2. Save this code in a file named hello.cpp to the your Cygwin home directory:
    C:\Cygwin\home\yourHomeDirectory
  3. Start Cygwin by selecting the Cygwin Icon Cygwin Bash Shell from the Start menu.

    In the terminal window, also known as the console window, you type commands like cd to change directories, ls to list files and pwd to print the working directory.

  4. In the command window, type the ls command to list all your files and verify your hello.cpp source code file is listed.
  5. Compile the hello.cpp program by typing the following command at the command prompt and then pressing the Enter key:
    g++ -o hello hello.cpp
    
  6. To run the program type:
    ./hello
    After running the command, you should see a window displaying, "Hello, World!".
  7. Submit your hello or hello.exe file (NOT hello.cpp) to Canvas as part of the next lab.

When finished, please help those around you.

Console Input and Output

  • We have been using cout to display information on our terminal windows
  • cout sends data to standard output, which is usually the terminal (console) window
  • The "<<" takes data from its right side and sends it to the console
  • Most basic data can be output to the console including
    • Variables
    • Literals
    • Expressions (which can include all of above)
    • Strings
  • We can display multiple values in one cout statement
  • Each data item must be separated with a << operator
  • For example:
    int numberOfDragons = 3;
    cout << numberOfDragons << " dragons." << endl;
    
  • Three values are output:
    • The value of the variable numberOfDragons
    • A literal string " dragons."
    • An end-of-line (newline) character
  • In the above example endl is a special word for an end-of-line (newline) character
  • Notice that the last letter of endl is an "el" and not a one
  • Another way to output an end-of-line (newline) is to use "\n"
  • For example:
    int numberOfDragons = 3;
    cout << numberOfDragons << " dragons.\n";
    

User Input

  • So far we have used an assignment operator "=" to assign a value to a variable
    int numberOfDragons = 3;
    
  • Another way to assign a value to a variable is to read it from the console
  • The keyboard input console is called cin (console input)
  • We use the >> operator with cin to send data to a variable
  • For example:
    cin >> numberOfDragons;
  • In this example, whatever valid integer number the user types is stored in the variable numberOfDragons

Prompting Users

  • Good programming practice is to always "prompt" users for input like:
    cout << "Enter number of dragons: ";
    int numberOfDragons;
    cin >> numberOfDragons;
    cout << "You entered " << numberOfDragons
         << " dragons\n";
    
  • Note that we do not put a newline after the prompt
  • The prompt waits on the same line for keyboard input like:
    Enter number of dragons: _
  • Where the underscore above denotes where keyboard entry is made
  • Every cin should have a cout prompt before it

Check Yourself

  1. The following code displays ________.
    int numberOfGames = 12;
    cout << numberOfGames << " games played.\n";
    
  2. Before getting input from a user, common practice is to display a(n) ________.
  3. True or false: the << and >> always point in the direction the data is flowing.

Exercise 2: Adding Two Numbers (8m)

In this exercise we will write a program to add two numbers together. When it runs, the program acts like this:

Enter the first number: 2
Enter the second number: 3
The sum of 2 and 3 is 5.

I suggest that you compile after each step so you know where an error is located if you make a mistake.

Specifications

  1. Copy the following program into a text editor, save it as variables.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. In main(), declare an int variable named num1 and assign it a value of 0:
    int num1 = 0;
    
  3. Add code to display a prompt to the screen:
    cout << "Enter the first number: ";
  4. Add a statement to input a new value for the variable and store it in memory:
    cin >> num1;
  5. Declare a second variable of type double named num2 and assign it a value of 0.0:
    double num2 = 0.0;
  6. Add code to display a prompt to the screen:
    cout << "Enter the second number: ";
  7. Add a statement to input a new value for the variable and store it in memory:
    cin >> num2;
  8. Declare a third variable of type double named total and assign it the result of adding the two variable together:
    double total = num1 + num2;
  9. Write another statement that displays the result of adding the two numbers together:
    cout << "The sum of " << num1 << " and "
         << num2 << " is " << total << ".\n";
    
  10. Compile and run your program to make sure it works correctly.
  11. Submit your variables.cpp source code file to Canvas as part of the next lab, 13.

When finished, please help those around you.

Completed Program

Completed program
Comments