Setting and using up the software you need for CSCI 104 CSCI 104 Teaching Team August 30, 2013 Abstract Visual Studio includes its own C++ compiler, it is good practice to utilize a second compiler, especially one such as GCC which is cross platform and free. When we evaluate your code in this class, we will always compile it using GCC, so it is your responsibility to ensure that it works with GCC, even if you developed it using Microsoft Visual Studio. For developing code in C++, the following tools are needed: This document is intended to get you started with the compilers and tools you’ll need for your work in CSCI 104. You will need a C++ compiler (we strongly recommend the freely available Gnu GCC/G++), along with a debugger and probably a make utility. Under Windows, the default solution is Cygwin, though you could also try MinGW, if you prefer. • gcc-core C compiler In addition, you will need a decent development environment and/or powerful text editor: we recom• gcc-c++ C++ compiler mend Microsoft Visual Studio, Eclipse, Emacs, or • gdb GNU Debugger Vim. This document gives you advice on how to set these • make Make utility up to work natively on Windows. For those of you trying to get started quickly, we also provide a VirCygwin will provide a way to easily install and use tual Machine which you can run on any operating these tools. system. It will open a Virtual Ubuntu system inside your operating system that comes with all the soft- 1.1 Installing Cygwin ware installed. This document also describes how to Cygwin can be downloaded from the Cygwin webuse the Virtual Machine. site3 . You should install a 32-bit version if you are on 32-bit Windows, and a 64-bit version if you are on 1 G++ on Windows: Cygwin 64-bit Windows. The Cygwin installer, every time it is run, will allow you to add or remove packages to This section is intended to get you quickly started your Cygwin installation. with C++ programming on your Windows1 machine. You should keep this installer executable for when Cygwin2 is a collection of tools which provide a you need to add or remove packages to your Cygwin Linux look and feel environment for Windows. It install. contains a package manager that makes it easy to install a number of programs. To develop code in 1.2 Installing Packages C++, we need a C++ compiler. Although Microsoft When you run the Cygwin installer, you will eventu1 If you use Linux, you probably already have all these inally get to a package selection screen, similar to that stalled, or know how to install software yourself. A guide for Mac will be added soon. 2 Cygwin Homepage http://www.cygwin.com/ 3 32-bit: http://cygwin.com/setup-x86.exe, 64-bit: http: //cygwin.com/setup-x86_64.exe 1 2 Setting Environment Variables The PATH environment variable tells Windows where to look for programs that are run by name either at the command line or from within other programs. To edit your PATH, perform the following: Figure 1: Selecting packages to install. seen in Figure 1. To select and install a package, do the following: Figure 2: Getting to environment variables in Windows 8. 1. Search for the package you want to install. 2. Click the ‘+’ next to ‘Devel/Default’ to expand the category. 2.1 Windows 8 1. Search settings (WIN + W) for path (Figure 2). 3. You can select packages to install by unchecking the ‘skip’ label next to them. This will change it to the version number of the item to be installed4 2. Select ‘Edit the system environment variables’. 3. Select ‘Environment Variables‘ (Figure 3). 1.3 4. In the ‘Environment Variables’ dialog, under the ‘System Variables’ panel, select the ‘Path’ variable and click ‘Edit’. (Figure 4) Using Cygwin The programs that Cygwin installs will reside in its installation directory in a folder named bin. To use Cygwin’s Linux emulation, run the Cygwin.bat script from the command line5 or using PowerShell (an improved Windows command line)]6 Additionally to the Linux environment, you can also add the Cygwin bin directory to your system PATH, allowing Windows to easily find and execute programs installed via Cygwin. This is described in Section 2. 5. Add the location of the ‘bin’ directory to the end of the Path variable (Figure 5). It is very important that you do not remove the other entries in this field. Locations are separated by semicolons. The default will be similar to C:\cygwin\bin 2.2 Windows 7 1. Open the Control Panel and select ‘System’. 2. Select ‘Advanced system settings’ (Figure 6). 4 Note that for some items, such as g++, there may be several options available to install. Choose the package that begins with gcc instead of others (e.g mingw or cygwin32). 5 XP and earlier: start → run → cmd, Vista and later: start → (search) cmd 6 Vista and later: start → (search) powershell 3. Select the ‘Advanced’ tab and click ‘Environment Variables’. 4. Proceed as in Section 2.1 starting from item 4. 2 Figure 6: Advanced system settings 2.3 Windows Vista and Earlier Please follow the this guide: http://java.com/en/ download/help/path.xml to learn how to get to editing the PATH variable. You may then follow the steps from Section 2.1 starting from item 4. Figure 3: Environment Variables 3 Verifying the Installation Once you have added Cygwin (or MinGW) to your system PATH (or if you believe that things are already installed and working), you can verify that everything is working by doing the following: • From the command line, type g++ --version and verify that version information is output. If Windows cannot find g++, you did not set up your PATH correctly. • From the command line, type gdb --version and verify that version information is output. If Windows cannot find gdb, you did not set up your PATH correctly. Figure 4: Editing the Path • From the command line, type make and verify that make complains of no input files. If Windows cannot find make, you did not set up your PATH correctly. If all of this succeeded, then you are ready to move on to the next sections of this document. Figure 5: Adding the directory 3 4 Installing G++ on Mac 4.1.2 Installing Homebrew This section is intended to get you quickly started It is very easy to install Homebrew. Open your terwith C++ programming on your Mac. We’ll be in- minal, and run the following command: stalling GCC 4.8.1 through a tool called Homebrew. In Section 5, we will describe how to set up Eclipse ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)" to use this newly installed compiler. If you want an additional guide on all of the If this doesn’t seem to do anything, try killing it following steps, excluding installing GCC, see (CTRL C) and running it again. this guide: http://www.moncefbelyamani.com/ how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/ and ignore anything about installing Ruby (stop 4.2 GCC after setting up git). 4.2.1 Installing GCC 4.1 Homebrew As mentioned before, installing packages with Homebrew is very easy. First, we will add the reposiHomebrew “installs the stuff that you need that Aptory from which the GCC package is available, so ple don’t”. It is not unlike Ubuntu’s apt-get, where that Homebrew knows where to find the package we one can install packages easily from repositories. Inwant. The repository is at https://github.com/ stead of having to download, configure, and install Homebrew/homebrew-versions. We do this by using something yourself, all you need to do is run one comthe brew-tap command. mand, and Homebrew will take care of the rest for Keep your terminal open, and run the following you. command. For more information on how brew-tap works, visit the Homebrew docs at https://github. 4.1.1 Pre-requisites com/mxcl/homebrew/wiki/brew-tap: 7 Homebrew requires that you have either Xcode8 or the Xcode command line tools9 installed on your Mac. Xcode is a free integrated development environment similar to Eclipse designed by Apple and mainly intended for IOS development or targeting the clang compiler (in this class we’ll focus on gcc). Xcode is quite a big install, so if you do not want to install it you can get away with just installing the Xcode command line tools. See http://stackoverflow.com/questions/ 9329243/xcode-4-4-command-line-tools for instructions on how to install the command line tools regardless of whether you have Xcode installed. If you want to skip doing any reading, download the Xcode command line tools from http://developer. apple.com/downloads/index.action. 7 Homebrew brew tap homebrew/versions Next, we will actually install the GCC package. Run the following command: brew install gcc48 It might take a while before the installation is complete. When done, run the following: gcc-4.8 --version The result should look like this: website http://brew.sh// gcc-4.8 (GCC) 4.8.1 Copyright (C) 2013 Free Software Foundation, Inc. 8 https://developer.apple.com/xcode/ 9 http://developer.apple.com/downloads/index.action 4 4.2.3 USC Wireless Warning (Advanced) Aliasing g++ If you prefer calling g++ directly, you can also create a bash alias, as such: Many people have had issues running the brew install commands while connected to USC Wireless. If you are having trouble, you can either try using a wired connection, a different wireless connection, or do the following: alias g++="g++-4.8" alias gcc="gcc-4.8" Put these two lines in the end of the file “˜/.bashrc”, and run: 1. Download http://ptzlabs.com/cs104/ homebrew-cache.zip source ~/.bashrc 2. Open Finder, press CMD (command) + SHIFT + G and type /Library/Caches/Homebrew For more information on bash alias, take a look at the GNU Docs: http://www.gnu.org/software/ bash/manual/html_node/Aliases.html. 3. Extract the contents of the .zip you downloaded inside of the folder you opened in the previous step. Do not extract any of the .tar.bz2 or .tar.gz inside of the .zip folder. 5 Installing Eclipse This section covers installing Eclipse on Windows. It assumes that you already have a valid GCC installation (i.e., running g++ --version from the command line produces some information about GCC). If not, go back to Section 1. Eclipse is an integrated development environment (IDE) that provides a graphical user interface (GUI) to develop and debug your code. Eclipse is not as fully featured of an IDE as Microsoft Visual Studio, but has the advantage that it is both cross-platform and free to use. Using an IDE over a text editor (e.g. Emacs, Vim, Sublime, Notepad++, etc) can make developing code easier as they often come with built-in text completion and visual debuggers. IDEs usually also abstract away the build process, which can be confusing when first learning C++ (but is ultimately very important). This should look like figure 7 4. Run brew install gcc48 in the Terminal as instructed above. Figure 7: Manually setting up the Homebrew downloads. 5.1 Pre-requisite: Java Runtime Environment Eclipse is a Java application and requires the Java Runtime Environment (JRE) to run. You can downTo compile with the newly installed G++ compiler, load this from the Java downloads website10 . Select use g++-4.8. 4.2.2 Using G++ 10 Java Download http://java.com/en/download/manual. jsp?locale=en g++-4.8 test.cpp -o test.out 5 5.4 32-bit if you are on a 32-bit version of Windows and 64-bit if you are using a 64-bit version. Install the JRE (pay attention during the installer, it will likely want to install an ASK toolbar which you probably don’t want) and test your installation by typing java -version at the command line. If you get back some information about your Java version, you have installed the JRE correctly. If after installing the JRE it does not add itself to your PATH (java -version gives an error), follow the instructions on the Java website11 and add the location of the bin folder within your Java installation to the system PATH. (See also Section 2.) 5.2 If Eclipse complains about not being able to find a Java Runtime Environment, you most likely installed different versions (32 vs 64 bit) of Eclipse and the JRE. Make sure you install the same type for both of them. 5.5 Get Eclipse 5.5.1 One-time: Setting PATH Variable This change only needs to be applied once. We will need to tell Eclipse where we installed our compilers. First, let’s find out where GCC is installed. Run the following command in Terminal: which gcc-4.8 It should look something like /usr/local/bin/gcc-4.8. Copy the path before /gcc-4.8, that is, /usr/local/bin. Install Eclipse • In the Menubar, find Eclipse → Preferences. Since Eclipse is a Java application, it does not need to be explicitly installed on your system. Simply unzip the downloaded file and place it wherever you would like Eclipse to exist. If you wanted Eclipse to live amongst other installed programs, you could create an Eclipse folder in C:\Program Files\ or C:\Program Files (x86)\ (depending on your computer architecture and the version you downloaded) and unzip the contents there. 11 PATH Configuring Eclipse on a Mac This section of the guide assumes you’ve already read and followed the Eclipse setup guides. To make sure that Eclipse uses the compiler that you just set up properly and not any other (for example, XCode includes a really old version of GCC), we need to configure some settings. Download the latest version of the Eclipse CDT (C/C++ Development Tooling) from its website12 (download links will appear on the right). Make sure to install the 32-bit version if you are using a 32bit Windows installation and the 64-bit version if on Windows 64-bit. If you do not install the version for the same architecture type (32 vs 64 bit) as you did for Java, you will get an error when you attempt to run Eclipse for the first time. If you encounter this, double check that you have the same (32 or 64 bit) versions of the JRE and Eclipse installed, and that they are correct for your Windows version. 5.3 Troubleshooting • In the sidebar of the Preferences window, find C/C++ → Build → Environment. • Press “Add” on the right. • Put PATH under “Name”, and what you just copied (usr/local/bin) under “Value”. • Press OK. instructions http://java.com/en/download/help/ path.xml 12 Eclipse CDT Kepler http://www.eclipse.org/ downloads/packages/eclipse-ide-cc-developers/keplerr • Make sure “Append variables to native environment” is checked. 6 5.5.2 Per-project: Setting Compiler This change will need to be applied every time you create a new project under Eclipse. We need to specify the compilers to which our program should compile in. • In the “C/C++ Projects” pane, find your project. Right click on it, and press “Properties”. • In the sidebar of the Preferences window, find C/C++ Build → Settings. • Change the “Command” of each of the tool from gcc to gcc-4.8, and g++ to g++-4.8. • Press OK. 6 Figure 8: Creating an empty C++ project in Eclipse. A first simple Eclipse Project 6.2 Enabling C++11 Support C++1114 is the latest standardized version of the C++ programming language and introduces several new features aimed at improving the language. If you would like to enable support for C++11 in eclipse, you must do the following after creating a project: This section will explain how to create and compile a simple program using Eclipse CDT. You should have already set up Eclipse and GCC are your computer before reading this. If you have not, go back to Sections 1 and 5. 1. Right click your project and select Properties 6.1 Creating a Project 2. Select Configuration → [ All Configurations ] After starting up Eclipse, you can create a new project by selecting File → New → C++ Project. By default, projects will be created in wherever you set up your workspace to be when first starting Eclipse, placed inside of folders named the same as the project. Select Executable → Empty Project for the project type and Cygwin GCC for the Toolchain13 . If you do not see Cygwin GCC in the Toolchains list, you likely did not add it to your system PATH variable. Ultimately your project creation should look something like Figure 8. 13 If 3. Go to C/C++ Build → Settings → Tool Settings → Cygwin C++ Compiler → Miscellaneous → Other Flags and add -std=c++11 (see Figure 9a). 4. Go to C/C++ General → Paths and Symbols → Symbols → GNU C++ → Add... and type or copy GNU EXPERIMENTAL CXX0X (two underscores leading and trailing) into the Name field, leaving Value blank (see Figure 9b). 14 C++11 you used MinGW instead of Cygwin, select that option. 7 Wiki Page http://en.wikipedia.org/wiki/C++11 (a) Enabling C++11 for the compiler. (b) Enabling C++11 auto-completion for Eclipse. 8 6.3 Your First Program 6.5 Running Compiled Code To add a new source (.cpp) file to your project, ex- To run a successfully compiled program in Eclipse, pand your project in the Project Explorer, right click do any one of the following: your project, and select New → Source File. For this • Click on the play button in the quick access toolexample, we will name the file main.cpp. bar. Eclipse will auto-generate some documentation at the top of your newly created file. You can expand • Select your executable in the Binaries folder of or collapse this by clicking the small plus (+) sign in your project, right click, and select Run As → the margin. Local C/C++ Application. The code in Figure 9 will print the numbers 0 to 10 along with some text. • Press CTRL + F11. Figure 9: Simple C++ Program 7 #include <iostream> Creating a simple project in Microsoft Visual Studio This section is intended to get you familiarized with int main() C++ programming using Microsoft Visual Studio15 . { This IDE has core project creation features including for( int i = 0; i < 10; ++i ) a code editor, debugger, and designer. std::cout << "Iteration " << i << std::endl; Visual Studio, like other IDEs, allows you to write, return 0; edit, compile, and debug code in a broad range of } programming languages. It is an Integrated Development Environment, which allows programmers to create a variety of projects, including user interface applications and websites. For the purposes of this 6.4 Compiling a Project class and this guide, we will focus on the basic usC++ programs need to be compiled before they can age of Visual Studio to create console programs using be run. To compile a program in Eclipse, you can do C++. any of the following (be sure to save your work first): 7.1 • Click on the hammer icon in the quick access toolbar. Creating a Project in Visual Studio For this exercise, we will be printing out the phrase “Hello World!”. (Hey, you get some variety compared to the Eclipse example.) To begin writing a program in Visual Studio, you must first create a new project. • Select Project → Build All. • Press CTRL + B. If you have any errors in your code, the Console 1. At the top left corner, click File. Select New, and will display the error and warning output from the then select Project. A dialog box will appear. compiler. You can also view these by going to the 2. In the left pane of the dialog box, click on Win32 Problems panel at the bottom of your screen. If evunder the Visual C++ section. erything compiles correctly, you should have no errors 15 http://www.microsoft.com/visualstudio/eng/ in your Problems panel and see Finished building products/visual-studio-express-for-windows-desktop target in your Console. 9 3. Select the Win32 (or Win64) Console Application option, and name your project. You can name it anything, but remember to keep it simple and easy to remember (e.g., “Hello World”). source file. To do so, right click Source Files under your project name. Select Add New Item. Figure 12: Adding a Source File Figure 10: Project Creation Dialog Box 2. A dialog box will appear. Under Visual C++ on the left side, click Code. Select C++ File and name your source file. Most people use “main” to indicate where the core of the program code sits. 4. On the Application Settings page under Additional Options, check Empty Project. There should be a message at the bottom that says “Creating project ‘Hello World’ . . . project creation successful.” This will ensure that your program does not have any initial miscellaneous code that could possibly affect the code compilation. 3. A blank page will appear. As an example, we could enter the same program as in our Eclipse introduction. Figure 13: Simple C++ Program #include <iostream> int main() { std::cout << "Hello World! " << std::endl; return 0; } In Visual Studio, your screen should now look like Figure 14. Figure 11: Application Settings 7.3 7.2 Writing Code for your Project Building Your Project To see how your program works, you must build the 1. Your project will appear on the screen. To begin code. This includes compilation and execution of the writing code for your program, you must add a project. 10 will see options for different break points. There are several types of break points. One type is a conditional break point, which will stop the program when that condition is true. Figure 14: Main Source File 1. Click on Build at the top of the screen. Select Build Solution. Figure 15: Debugging in Visual Studio 2. If your project compiled successfully, the dialog box at the bottom of the screen will say “Build: 1 succeeded, 0 failed” and a terminal will pop up. 2. Right click on your project name, and then select Debug. 3. If your project did not compile successfully, make sure that all of your syntax is correct (e.g., no missing commas or semicolons). You can also debug your code to see where your program fails to build. 7.4 8 Useful Text Editors for writing C++ code This guide covers installing (on Windows) and ba- Simple Debugging in Visual Stu- sic usage of various text editors that support C++. dio It assumes that you already have a valid GCC and make installation (i.e., running g++ --version from the command line produces some information about GCC and make complains of no input files). If not, go back to Section 1. Using a text editor instead of an integrated development environment (IDE) provides a more light weight editing experience. Good text editors can usually be customized to have almost all of the functionality of an IDE, but are often very bare bones out of the box. This guide will cover a few popular text editors. (If you are still using gedit or notepad to write C++ code, then today is the day to stop. You out yourself as an amateur by doing so.) 1. To set a break point, click on the tray on the side. While IDEs will often create and manage makefiles A red bubble should appear where you clicked for you, you will need to do this manually with text your mouse. If you right click on the tray, you editors. Visual Studio has a built-in debugger. A debugger allows you to set break points in your code that will allow you to see where your code may not function the way you intended. As you go along, stopping at breakpoints or stepping through your program, you can keep track of variables, and the values they are assigned. This may help you figure out much more quickly where something goes wrong. When you begin the debugging process for a specific program, the code will execute up until the statement where the first break point has been set. The break point statement will not be executed. 11 8.1 Emacs • U. of Chicago Emacs Tutorial http:// www2.lib.uchicago.edu/keith/tcl-course/ emacs-tutorial.html. • Mastering Emacs http://www. masteringemacs.org/articles/2010/10/ 04/beginners-guide-to-emacs/. • Xah Emacs Tutorial http://ergoemacs.org/ emacs/emacs.html. 8.2 Vim Figure 16: Emacs session integrated with GDB. Emacs is one of the most popular text editors available and is incredibly extensible and portable (see Figure 16 for a screenshot). Emacs, along with Vim, are more difficult to get started with than Notepad++ or Sublime, but offer a user experience that is unique and preferred by many. Figure 17: Editing multiple documents with GVim. 8.1.1 Installing Emacs Emacs can be downloaded from the GNU Emacs Windows page16 . You will want to download and extract the emacs-24.3-bin-i386.zip file, located at the bottom of the page. To run Emacs, launch the runemacs.exe program within the bin folder. If you want to create shortcuts to Emacs, run the addpm.exe program. For more information on how to install Emacs, see the installation guide17 . Vim, like Emacs, is an extremely customizable and portable text editor. Vim is almost always found on default installations of Linux distributions. While Vim is a command line only editor, GVim is a graphical front-end that provides a more traditional experience on all environments that support Vim (see Figure 17 for a screenshot). 8.2.1 8.1.2 Installing Vim Using Emacs Vim (including GVim) can be downloaded from the 18 There are many tutorials available for Emacs and the Vim download page . You should download and install the gvim74.exe program. Internet is a great guide for how to use it: • Stanford Emacs Tutorial http://cmgm. stanford.edu/classes/unix/emacs.html. 16 Emacs download 8.2.2 http://ftp.gnu.org/gnu/emacs/ windows/ 17 Emacs Windows Install Guide http://www.gnu.org/ software/emacs/windows/Installing-Emacs.html Using Vim Vim has two modes of operation: insert and command. Insert mode is a typical text editing mode 18 Vim pc 12 Download Page http://www.vim.org/download.php# that allows text to be inserted and deleted. Command mode is where the true power of Vim resides, and provides convenient ways to navigate and manipulate text. By default, command mode is entered by pressing Esc, and insert mode is entered from command mode by pressing i. Documents can be saved from command mode by typing :w, and closed by typing :q. Vim supports tabbed editing and can open new tabs by typing (from command mode) :tabe FILENAME. From command mode, you can use the key sequence gt and gT to cycle forwards and backwards between tabs. For much more information on using Vim, see one of these pages: Notepad++ is a text editor for Windows that supports multiple languages and is very easy to use, especially coming from a Windows background. See Figure 18 for a screenshot. 8.3.1 Installing Notepad++ Notepad++ can be downloaded and installed from its website19 . You can either choose to download an installable package, or a zip package that does not need installation. 8.3.2 Using Notepad++ Notepad++ requires no extra setup or customization • Interactive Vim Tutorial http://www.openvim. to provide a good coding experience (though it can indeed be customized further). Its use is very simicom/tutorial.html. lar to any other text editor on Windows. For more • Vim Tutorial and Introduction http: information, see the Notepad++ Resources page20 . Notice that because it is more lightweight, it may //blog.interlinked.org/tutorials/vim_ not be quite as effective when used by an expert. tutorial.html. • 25 Vim Tutorials http://net. 8.4 Sublime Text tutsplus.com/articles/web-roundups/ 25-vim-tutorials-screencasts-and-resources/. Sublime is a newer and increasingly popular cross platform text editor. It offers the flexibility of Emacs 8.3 Notepad++ and Vim but with a more intuitive user interface. It comes with many features that would require plugins for Emacs or Vim without any extra setup (see Figure 19 for a screenshot). Unlike the other options listed here, Sublime Text is not free; it has an evaluation period and then requires a license. 8.4.1 Installing Sublime Text There are two versions of Sublime available, Sublime Text 221 and Sublime Text 322 , currently in beta. Figure 18: Notepad++. Editing multiple documents with 13 19 Notepad++ Download http://notepad-plus-plus.org/ download/v6.4.5.html 20 Notepad++ Resources http://notepad-plus-plus.org/ resources.html 21 Sublime Text 2 Download http://www.sublimetext.com/ 2 22 Sublime Text 3 Download http://www.sublimetext.com/ 3 computer. It is also very useful to have SSH installed so that you can set up a public key system that will allow BitBucket to trust your computer without needing a password. To find out how to do this, please visit the git-scm website25 and look up the information for your operating system. To summarize some of the steps involved, here are the instructions for Windows, Linux, and Mac. Please Read Please read each section before you actually do anything. Do not blindly start entering commands without reading what they do in the guide. Figure 19: Editing multiple documents with Sublime. 8.4.2 Using Sublime Text For information on using Sublime Text and to read its documentation, visit the Sublime Text support website23 . 8.5 Compiling For all of the text editors listed, compilation (by default) must be done externally at the command line.24 Figure 20: Installing git with Cygwin. One of the best ways to do this is by creating makefiles and then simply typing make to compile and link your programs. For an excellent tutorial on creating a makefile, see 9.1.1 Windows http://mrbook.org/tutorials/make/. To install git and ssh on Windows, you will use Cygwin, which you should already have used to install things like g++ and gdb. 9 Setting up Git and BitBucket As you should remember from the Cygwin installation instructions, running the original executable you This section covers installing and setting up git as used to install Cygwin will allow you to add or remove well as creating a BitBucket account and setting up packages to your installation. a repository that can be accessed by the CS 104 TAs 25 http://git-scm.com/book/en/ for grading. Getting-Started-Installing-Git 9.1 Setting up Git and SSH In order to work with your BitBucket account, you will need to have git installed and available on your 23 Sublime Text Support http://www.sublimetext.com/ support 24 However, note that it is possible to customize them to compile and debug within the editor. Figure 21: Installing SSH with Cygwin. 14 You will now need to add the following packages to your Cygwin installation: Figure 22: Example of colored prompt showing git branch. 1. git Search for git and install git from the Devel category (see Figure 20). 2. git-completion You’ll only need to do this once. This lets git know who to say you are when it creates commit messages. Search for git and install git-completion from the Devel category (see Figure 20). STOP Review Things so Far At this point you should verify that git is properly installed using the appropriate command line interface for your operating system. Ensure you can type git as well as ssh without an error about not finding either. 3. openssh Search for openssh and install openssh from the Net category (see Figure 21). 4. dos2unix Search for dos2unix and install dos2unix from the Text category. 9.1.2 Linux 9.2.1 (Optional) Coloring your git prompt This is an optional step that lets you color your command line interface to emphasize which git branch you are currently in (see Figure 22). This is highly recommended as branching will be an important part of using git. On a Debian based Linux such as Ubuntu, installation of git is extremely easy: sudo apt-get install git. If you are using the class VM, it is already installed. SSH should already be installed on your Linux dis- Windows (Cygwin) tribution. You will need to add the line listed at http: //pastebin.com/9hqwkru4 to the end of your ~/.bashrc file (this will be somewhere such as 9.1.3 Mac C:\cygwin64\home\username\.bashrc). Open the Mac users should install the most recent file using a text editor such as wordpad (don’t use version of the git-osx-installer from notepad for this) and paste the contents linked above http://code.google.com/p/git-osx-installer/ at the end of the file. downloads/list. After you have saved the file, run the following command in your Cygwin terminal: 9.2 Git Configuration dos2unix ~/.bashrc You must then restart your Cygwin terminal. Once git is installed, you should configure it to let it know who you are: Path Separators You may have noticed that in this guide sometimes paths are separated by / and sometimes by \. This is because UNIX based systems such as Linux and Mac (and your Cygwin install on Windows) use the forward slash (/), while Windows (while not running Cygwin) use the backwards slash (\). • Set up your name (include quotes): git config --global user.name "Your Name" • Set up your email (include quotes): git config --global user.email "your@email.com" 15 The Tilde Key (˜) and Useful UNIX Commands In a UNIX environment (Mac, Linux, and Cygwin), the ˜refers to your home directory, or the default directory when you open your terminal. they are shared with less than 5 total users, as well as free public repositories. In this course you will use a private repository to which you are the sole contributor, sharing access only with the CS104 TA grading account. • mkdir, or make directory, is used to create folders 9.3.1 • cd, or change directory, is used to change the working directory If you do not already have a BitBucket account, you will need to create one at the BitBucket website26 . Remember to confirm the email address that you use. • pwd, or present working directory, will tell you where you currently are 9.3.2 • .. is used to denote moving up one folder (e.g.: cd ..) Once you have logged in, visit your dashboard and click on Create repository to create a repository (Figure 23). Creating an account Creating your CS104 repository • . is used to denote the current folder (e.g.: ./my program) • ls is used to list the files in the current directory. You can read more about basic UNIX commands here: http://mally.stanford.edu/ ~sr/computing/basic-unix.html Figure 23: Creating a repository from your dashboard. Your repository must be named cs104 fa2013 Linux (see Figure 24). Failure to name your repository If you are on the VM, we have already correctly could interfere with grading of your assigndone this for you. If not, you can follow ments. this guide: http://code-worrier.com/blog/ git-branch-in-bash-prompt/. 9.3.3 Editing Settings of Your Repository Mac In order for us to be able to access your repository Follow the guide here: http:// for grading, you must do two things in the settings martinfitzpatrick.name/article/ page for your newly created repository. You can get add-git-branch-name-to-terminal-prompt-mac. to this page by clicking the gear in the upper-right of When the guide refers to using ‘your favorite editor,’ your repository overview (see Figure 25). this is any text editor you want to use. Once in your settings, you will need to do the following two things: 9.3 BitBucket 1. In Access management, give the user cs104 read BitBucket is a website that offers code hosting using access to your repository (see Figure 26). git or mercurial, which are both version control 26 BitBucket sign up https://bitbucket.org/account/ systems. In this class, we will use git. BitBucket offers unlimited free private repositories, so long as signup/ 16 Figure 27: Add usc.cs104@gmail.com as an email hook. user name and password each time you interact with the remote repository, you can use SSH to set up a public key pairing that will remember your identity. To see how to do this, please visit either the guide from GitHub27 (ignoring any GitHub specific information), or this guide from BitBucket28 . If you don’t feel like reading those guides, the steps here should get you through it with no problem (all to be done Figure 24: Creating and naming your repository. It through the command prompt): must be named cs104 fa2013. 1. If you do not already have an ssh key (ls ~/.ssh shows no id rsa.pub), generate one by typing (all on one line, replacing the email with your own, including quotes): Figure 25: Click the gear icon (highlighted red here) to get to your project settings. ssh-keygen -t rsa -C "your email@example.com" This will prompt you to give your SSH key a pass-phrase, which is optional but highly recommended. 2. In Hooks, create an Email hook to email usc.cs104@gmail.com (see Figure 27). 2. (Windows Only) Adjust the permissions of id rsa.pub Failure to do either of these steps correctly could interfere with grading of your assignments! Type the following commands into your Cygwin terminal: cd ~/.ssh chgrp Users * chmod 700 id rsa cd ~ Figure 26: Add cs104 to your repository with read access. 3. Copy your id rsa.pub to the clipboard. On Windows, you can easily copy it after opening the file in notepad: start 9.3.4 SSH Key BitBucket requires authentication whenever you interact with it using git. Instead of typing in your 27 https://help.github.com/articles/ generating-ssh-keys#platform-all 28 https://confluence.atlassian.com/display/ BITBUCKET/Set+up+SSH+for+Git 17 Figure 29: Entering your SSH key on BitBucket. Figure 28: Getting to Manage account on BitBucket. notepad from the start menu, and open the id rsa.pub file located at C:\cygwin64 (or cygwin)\home\YOURNAMEHERE\.ssh. You will need to select All Files *.* instead of Text Documents *.txt to see the files. On Linux, you can easily copy it after opening the file in gedit: gedit ~/.ssh/id rsa.pub pastebin.com/mZcquN5S. The file you need to edit will be at a location similar to C:\cygwin64\home\username\.bashrc) It is suggested that for Windows you use a real text editor (see text editors section for some examples) or at least use wordpad, as notepad has trouble displaying the lines correctly. Remember to change the file type to All Files *.* so you can see the .bashrc. After you save your file using wordpad or your other text editor, run the following command from Cygwin: On Mac, you can copy the file directly using pbcopy, which will make it so you can paste immediately: pbcopy < ~/.ssh/id rsa.pub dos2unix ~/.bashrc 4. Attach your SSH key to your BitBucket account by logging into BitBucket and going to Manage account, found by selecting your avatar at the top right of the website (see Figure 28). You should then restart your command line, enter your pass-phrase once, and never have to enter it again. From the Account page, select SSH Keys → Add 9.3.5 Local Repository Creation key and paste your key after giving it a descriptive label, such as a nickname for the computer Now that your repository is set up with the proper name and access for the TA account, and you have set you are using (see Figure 29). up your SSH key, it is time to create a local version 5. Set up your system to automatically enter your of your repository on your computer. You can follow step by step directions on how to do this by selectpass-phrase for your SSH key. ing I’m starting from scratch on the Getting started If you are on Mac or Linux (Ubuntu), it will offer section of your repository Overview. to automatically remember the pass-phrase after Those steps, to be executed from the command line you have manually had to type it in once. or your git console, reprinted here, are: On Windows, you will need to edit your 1. Create a local project directory (folder) some~\.bashrc like in Section 9.2.1 and append where on your computer where you want to save (add to the end) the code here: http:// 18 your work. This is where all work for this class will reside. If you are using Cygwin, remember that all of your Cygwin files reside somewhere in C:\cygwin64\home\username\). On Mac and Linux, you can create this folder anywhere you would like. mkdir is the command to make a directory, which is followed by the path where you want to make it: mkdir this/is/just/an/example 1. Create a README file, e.g: echo "# This is my README" >> README.md 2. Add this to your locally staged commits: git add README.md Adding to your local repository is described in detail in Section 9.4.3. This tells git to start tracking changes for the file. 3. Commit this to your local repository: You can type pwd to see the current directory you are in (present working directory). git commit -m "First commit. README." 2. Change to that directory using cd Adding a Committing is described in detail in Section 9.4.3. The -m option tells git to use the message you supply as your description of the changes made. cd this/is/just/an/example 3. Initialize your local git repository: git init 4. Push your local changes to the remote repository for the master branch: 4. Add your BitBucket account as a remote repository for the locally initialized repository. git push -u origin master Assuming you have set up your SSH key, This tells git to push your local master branch you can get the SSH address of your to the remote origin, which is your BitBucket repository by selecting SSH from the droprepository. down menu on the right hand side of your repository overview. It should look someAfter performing your first commit, you will be thing like ssh://git@bitbucket.org/cs104/ able to push (send files to) and pull (get files from) cs104 fa2013.git. your remote repository very easily, without needing You can then use this to let your local git reposi- extra syntax. This is discussed more in Section 9.4. tory know about the remote one (all on one line, make sure you use the address for your reposi- 9.3.7 Git cloning tory and don’t just copy paste this example): If you have already done your first commit and find git remote add origin yourself in a situation where you need to recreate your ssh://git@bitbucket.org:cs104/ repository locally on your machine, or want to create cs104 fa2013.git a local copy on another machine (perhaps you accidentally deleted it), you will not need to go through all of the steps above. Instead, you can just use git 9.3.6 Your First Commit clone29 to set up your local copy of your BitBucket The first commit you make to your repository will be repository. a README file. These steps are outlined on the BitRemember that you will need to generate an SSH Bucket website if you click Next after you performed key and attach it to your account for each computer the steps in I’m starting from scratch. These should (including virtual machines) that you use. be executed within your newly created project direc29 http://git-scm.com/docs/git-clone tory: 19 9.4.1 Attention Status of Local Repository Cloning is something you can do only if you have fully initialized a repository on your BitBucket account by doing the first commit and push. If you need to delete your local copy or want to set up on another computer, that is the time when you would use git clone to set things up. You can check the status of a local repository by typing git status30 , which will display differences between your HEAD commit and what it currently sees. This will display information such as which files have changed and which files are new. To clone a repository, you will need to do the following: Two of the most important git commands are push31 , which sends locally staged commits to a remote repository, and pull32 , which brings remote changes to a local repository. Although the initial commit to your repository was a bit verbose, future pushes can usually be done simply by typing git push. Remember that push sends locally staged commits and will not send anything if you have not committed changes. push will also fail to work if there are remote changes which you have not merged into the local repository by performing a pull. Pulling files merges them into your local repository. git is pretty good at handling these merges automatically, but occasionally you may get conflicts between the remote and local versions of a file (it is unlikely this will occur during this course, but take a look at something like http://stackoverflow.com/questions/161813/ how-do-i-fix-merge-conflicts-in-git if it does). 9.4.2 1. If you do not already have an SSH key for the computer you are on, create one and add it to BitBucket using the procedure in Section 9.3.4 2. Go to your BitBucket overview page for your class repository 3. Click on the Clone button and select the SSH option. 4. Copy the clone command and paste it at the command line. For example, it might look like: git clone git@bitbucket.org:cs104/cs104 fa2013.git By default this will create a folder with the same name as your repository wherever you run the command. If you want to name the folder something else, you can either rename it later or specify a name when you clone, for example: Pushing and Pulling git clone git@bitbucket.org:cs104/cs104 fa2013.git MyFolderName 9.4 9.4.3 Working with Git Commiting Changes and Adding Files When you change files locally and want to push them There are many great online resources for learning to the remote repository, you must first stage them git as it is a very popular version control system. for the push by committing them locally. Remember Two good resources are: that you can use git status to see which files have been changed. • git-scm book http://git-scm.com/book To add new files to your local repository, use git • Atlassian tutorials https://www.atlassian. add filename33 . This will cause git to start tracking changes made to these files and enable you to push com/git/tutorial them to your remote repository. There are doubtless others that are also good, but 30 http://git-scm.com/docs/git-status these are quite comprehensive and easy to follow. 31 http://git-scm.com/docs/git-push 32 http://git-scm.com/docs/git-pull You will be using git a great deal in this course so 33 http://git-scm.com/docs/git-add it is worth your while to invest in learning it. 20 If you accidentally add a file you do not want 9.4.4 Renaming and Removing Files to add, and have not committed the changes yet, files are renamed with git mv old name you can use git reset HEAD filename to undo the Tracked 38 new name and removed (deleted) with git rm39 . 34 add . Git will attempt to figure out some of this automatWhenever you have files that have been added or ically if you forget to do it, but it is good practice to any files that are tracked and have been changed, use the git commands when modifying tracked files. you can commit those changes to the local repository with git commit35 . You can either pass commit a 9.4.5 Branching list of files to commit, or specify -a to commit all locally tracked and changed or added files. When Branches are points where you diverge from the main you commit, an editor will open, prompting you line of development to continue to work on things to enter a descriptive message about your commit. without messing up the main line. Imagine you are By default this editor is usually a variant of vim, working on an assignment and have a solution comwhich is a bit confusing to use. You can change piling but it is not complete. Instead of tampering it by typing git config --global core.editor with your partially correct solution, you could cre"editorname", where editorname is the command ate a branch that would leave your original work inyou would use to start your editor from the command tact and allow you to develop a separate line of code line. which could later be merged back into your original solution. If you want to continue using vim (or you haven’t Branching is one of the most powerful features of changed your editor), you should read the section of git, and is one you will become well acquainted with the class guide that talks about text editors for more in this course. information. The quick and dirty version is: ESC folThe default branch in git is the master branch. lowed by i to enter insert mode and type text, ESC A good practice to keep is to have your master in a followed by :wq to save and quit, and ESC followed state where it can always compile. When you read by :q! to quit without saving. the section about turning in code (see Section 9.6), If you don’t want to bother with the ed- you will see why this is especially important. In this course we will follow a branching model itor opening, you can specify a commit message directly by performing git commit -m "your where master is always stable and other branches message goes here" (either specifying the files or are used for development40 . You will merge these side branches into your master branch whenever you using -a for all as before). want to update your solution to an assignment, as It is good practice to commit often in small chunks (as you will read in the grading section), your master so that it is easier to undo commits and merge branch will always be considered for grading by the changes. Undoing commits can be a bit tricky, so staff. please read some guides on undoing the most recent commit36 or undoing commits in general37 . Creating Branches You should already have both local and remote master branches from earlier in this tutorial. Since we are advocating keeping master stable at 34 http://stackoverflow.com/questions/348170/ all times, you need to create other branches to deundo-git-add-before-commit 35 http://git-scm.com/docs/git-commit 38 http://git-scm.com/docs/git-mv 36 http://stackoverflow.com/questions/927358/ how-to-undo-the-last-git-commit 37 http://sethrobertson.github.io/GitFixUm/fixup.html 39 http://git-scm.com/docs/git-rm 40 http://nvie.com/posts/a-successful-git-branching-model/ 21 velop unstable code in, and then merge it into master when you are satisfied with it. To create a branch, type git branch branch name41 . You can optionally specify -b to immediately switch to that branch, otherwise you can switch to that branch (see Section 9.4.5) to work on it. When you create a branch, it will contain a copy of whatever is in the branch you split off from. You can view your created branches by typing git branch -a42 . When you create a branch, it will only exist locally and not on the remote repository. To push the branch to the remote repository, type git push origin branch name43 . This will allow you to push and pull changes to this branch just like your master. Viewing and Switching Branches To see which branch you are currently in, type git branch. You can see all local and remote branches you have by typing git branch -a. You can then switch to a branch by typing git checkout branch name. This will cause all files in your working directory to be replaced by those in the branch you switch to. If you want to go back and edit files in the branch you switched out of, switch to that branch. If you want to move files from one branch to another, you will need to merge branches. you would merge mycoolbranch into master, commit the changes, and then switch back to mycoolbranch to continue development without tampering with your partially working solution. To merge branches, do the following (using the mycoolbranch into master example): 1. First switch into the branch you want to merge into (the target of the merge): git checkout master 2. Now you will tell git to merge the branches: git merge mycoolbranch 3. Resolve any merge conflicts (more on this later) 4. Push the merged changes to your remote repository git push 5. (Optional) Switch back to your development branch and keep coding: git checkout mycoolbranch As you can see merging is quite a simple process, especially if you do not run into merge conflicts (cases where git cannot combine the differences in some file). Merge conflicts can only happen if you are concurrently developing in two branches at the same time. For this course, this is strongly discouraged as handling merge conflicts can be difficult. If you do run into this, please Merging Branches read up: http://stackoverflow.com/questions/ When you are working in a branch and have reached 161813/how-do-i-fix-merge-conflicts-in-git. a point where the code is stable enough to be merged into master (or some other branch), it is time to merge branches. Merging will make the two branches 9.5 Git Workflow Summary equivalent but will not delete either branch. In this class, it is suggested you follow the following Consider the case where you have split from your workflow: master branch to work on a homework assignment, creating the branch mycoolbranch. You have • Keep your master branch such that it can always reached a point in your work where you have a partial be compiled and always be turned in as a partial compiling solution to the assignment. At this stage solution 41 http://git-scm.com/docs/git-branch • Use a secondary branch to develop your solution in and merge it into master as soon as it becomes stable. Never develop code in your master branch. 42 http://stackoverflow.com/questions/12370714/ git-how-do-i-list-only-local-branches 43 https://help.github.com/articles/ pushing-to-a-remote 22 10.1 • Do not do concurrent development - keep to coding in one branch at a time, merging when you are happy with the state of it Installation The VM that we’re going to install is a customized Ubuntu 13.04 installation that comes with the most recent C++ compiler, libraries, debuggers, a graph• Perform many frequent small commits, occasion- ical performance analyzer, and an advanced IDE. If ally pushing to remote to back up your changes you have another Ubuntu installation from a previous class at USC, it is recommended that you switch to this one. 9.6 Turning in Assignments When you get an assignment, you will create a new 10.1.1 Step by step folder in the root directory of your repository with a 1. Download and install VirtualBox software specific name detailed by the assignment. The folder on your personal machine: https://www. name must be the same or there may be complicavirtualbox.org/wiki/Downloads. tions grading your assignment (we’ll be looking for 2. Download the CS104 Ubuntu image. specific folders when we run grading scripts). Mirror 1: https://www.dropbox.com/s/ Any work you have checked into your remote Bite82zpnkgj0m686m/CS104-VM.ova Bucket repository in the master branch, up until the Mirror 2: http://www.ultimatepenultimate. assignment deadline, will be used as your submission net/files/CS104-VM.ova for the assignment. There is no explicit turn-in procedure - anytime you do a push to your remote master, 3. Install VirtualBox Extension Pack from you can consider that turning in your assignment. here: http://download.virtualbox. You can turn it in as many times as you want up unorg/virtualbox/4.2.16/Oracle_VM_ til the deadline and we will use the version closest to VirtualBox_Extension_Pack-4.2.16-86992. the deadline time. Any changes you push after the vbox-extpack. deadline will be ignored for grading that assignment. 4. Open VirtualBox Manager. From File menu, As a backup, you can always submit your assignselect Import Appliance. ments in a zipped file through Blackboard by the assignment deadline. 5. Click on Open Appliance and point it to the downloaded image (CS104-VM.ova). 10 The CSCI 104 Ubuntu Virtual Machine If you are not sure you want to install the programs described previously as native programs on your system, and don’t want to work remotely on aludra (which we consider rather inconvenient), we strongly encourage you to use the Ubuntu44 virtual machine (VM) specifically provided for this class. You can install it on your laptop regardless of your operating system, and use it for the entire semester for labs and homework assignments. 44 http://www.ubuntu.com 6. Click next and then click import. The import process may take some time. 7. Once the import is finished click on Settings and go over the details. 8. Adjust the appropriate amount of base memory. Everything has to be in the green zone (Figure 30). 9. Make sure the VM has at least 2 CPU cores allocated (Figure 31). You can adjust this later to get the best results. 10. Turn 3D Acceleration ON (Figure 32). 11. Start the VM! Password is cs104 23 10.2 Troubleshooting In this section, we briefly go over common problems with VirtualBox and Ubuntu. 1. In the Settings menu, if there is a sign at the bottom of the window that reads “non-optimal”, it means you have made a wrong setting. Hover your mouse over the warning message to get the details. 2. Error “VT-x features locked or unavailable in MSR”: You need to enable Virtualization for your laptop. If you don’t do this, Ubuntu won’t be able to take advantage of all your CPU power. Usually virtualization is disabled by default on PC laptops and enabled by default on Mac laptops. Figure 30: VM mainboard settings (a) Enter the bios settings. This is different from laptop to laptop so you have to Google it and find the instruction for your make and model. For example something like this “Laptop HP dv6 bios virtualization”. Usually you have to keep pressing F2, F10, or something similar at the very beginning of your laptop power on. This is before Windows starts. (b) Find the Virtualization setting in the sub menus and set it to “ON” or “Enable” (Figure 33). Figure 31: Processor settings (c) Save and Exit. (d) Older laptops might not have a virtualization option. In that case switch back to single-core VM. Figure 32: Change display settings 24 Figure 33: Enable Virtualization in Bios 25