Setting up Eclipse for C/C++

IDEs are tools to make code development a lot easier, specially if your project has multiple files, classes, and functions. However, setting up the IDE can sometimes be as painful as developing complex codes without an IDE. This post will present a short tutorial about how to install and configure Eclipse for C/C++ on Windows 7 in a (hopefully) fairly painless manner. This tutorial is sequenced as follows:

  1. Installation
    1. Downloading the Java Runtime Environment.
    2. Downloading the GCC compiler.
    3. Downloading Eclipse.
  2. First steps with Eclipse
    1. Setting up a template (optional)
    2. Creating a new project
    3. Including libraries in your project

INSTALLATION

Downloading the Java Runtime Environment

To check if you have the Java Runtime Environment installed, go to java.com with either Internet Explorer or Firefox (Chrome will block the plugin) and click on “Do I have Java?”. Accept running all the pluggins and, If the website tells you you do not have java, you will have to download and install it from the link displayed on the website.

Downloading the GCC compiler

After the check is done, you will have to download the GCC compiler, which can be done from http://www.equation.com. On the side menu, there will be a link to Programming Tools, which after expanded shows a link to Fortran, C, C++. Click on this link and download the right GCC version for your system (32/64 bit), as shown in the following screenshot.

DownloadGCC

After downloading it, double click on the executable, accept the licence, and type “c:\MinGW” as the installation directory. This is important because this is the first folder where Eclipse will look for the compiler in your computer. Proceed with the installation.

Downloading Eclipse

Now it is time to download an install eclipse. Go to the Eclipse download website and download Eclipse IDE for C/C++ Developers. Be sure to select the right option for your computer (Windows, 32bit/64bit), otherwise eclipse may not install and even if it does it will not run after installed. If unsure about which version you should download, this information can be found at Control Panel -> System by looking at System type.

Download

After downloading it, extract the file contents to “C:\Program Files\eclipse” (“Program Files (x86) if installing the 32 bits version) so that everything is organized. Note that for this you will need to start WinRAR or any other file compression program with administrative privileges. This can be done by right clicking the name of the program on the start menu and clicking on Run as Administrator.

Now, go to C:\Program Files\eclipse and double click on eclipse.exe to open eclipse. In case you get an error message saying, among other things:

Java was started but returned exit code=13
...
...
-os win32
-ws win32
...

then delete the whole eclipse folder, go back to the eclipse download page, download eclipse 32 bit, and extract it as previously described. You should not see the same error again when trying to run eclipse.exe.

Now that Eclipse is up and running, it is time to use it.

FIRST STEPS WITH ECLIPSE

The first thing eclipse will do is ask you to choose a workspace folder. This is the folder where all your code projects will be stored. It should not matter too much which folder you choose, so using the default is probably a good idea.

Setting up templates (optional)

It is helpful to create a code template in order to avoid retyping the same standard piece of code every time you create a new file or project. Many scientific codes have similar imports (such as math.h and stdio.h) and all of them must have a main method (as any C++ code). If we create a code template with a few common imports and the int main function, we can just tell Eclipse when creating a new project to add these to a new .cpp file.

In order to create the mentioned template, go to Window -> Preferences. There, under C/C++ -> Code Style on the left panel, click on Code Templates. Under Configure generated code and comments, expand Files -> C++ Source File, and then click on New. Choose a meaningful name for your template (I chose “Cpp with main”) and type a short description. After that, copy and paste the template below under “Pattern”.

/*
File: ${file_name}

Author: ${user}
Date: ${date}
*/

#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    // Your code here.

    return 0;
}

Note ${file_name}, ${data}, and ${user} are variables, which means that they will be replaced by your file’s actual data. To see a list of the other variables that can be inserted in your template, click on Insert Variable…. Click Ok and Ok again and your template will be ready to be used!

Configuring_template

Creating a new project

Click on File -> New -> C++ Project. Under Project type choose Empty Project, then under Toolchains choose MinGW GCC, and, finally, type “project1” as your project name an click on Finish.

New_project

After your project is created, click on File -> New -> Source File. Type “say_something.cpp” (no quotes and do not forget the .cpp after the file name) as the name of your source file and choose the template you created as the template. The window should then look like this:

New_file

Click on Finish. If you used the template, replace the comment “// Your code here.” by “cout << “Yay, it worked!” << endl;”. Your code should look like the snippet below. If you have not created the template, just type the following code to your file.

/*
File: say_something.cpp

Author: bct52
Date: Jun 26, 2015
*/

#include <iostream>
#include <string>
#include <math.h>
#include <stdio.>
#include <string.h>

using namespace std;

int main()
{
    cout << "Yay, it worked!" << endl;

    return 0;
}

Now, build the code by clicking on the small hammer above the code window and, after the project is built, click on the run button (green circle with white play sign in the center). If everything went well, your window should look like the screenshot below, which means your code compiled and is runs as expected.

Project1_run

Including libraries in your project

When developing code, often times other people have had to develop pieces of code to perform some of the intermediate steps we want our code to perform. These pieces of code are often publicly available in the form of libraries. Therefore, instead of reinventing the wheel, it may be better to simply use a library.

Some libraries are comprised of one or a few files only, and can be included in a project simply by dragging the file into the Eclipse project. Others, however, are more complex and should be installed in the computer and then called from the code. The procedure for the latter case will be described here, as it is the most general case . The process of installation and usage of the Boost library with MinGW (GCC) will be used here as a case study.

The first step is downloading the library. Download the Boost library from here and extract it anywhere in your computer, say in C:\Users\my_username\Downloads (it really doesn’t matter where because these files will not be used after installation is complete).

Now it is time to install it. For this:

    1. Hold the Windows keyboard button and press R, type “cmd”, and press enter.
    2. On the command prompt, type “cd C:\Users\bct52\Downloads\boost_1_58_0” (or the directory where you extracted boost to) and press enter.
    3. There should be a file called bootstrap.bat in this folder. If that is the case, run the command:
      bootstrap.bat mingw
    4. In order to compile Boost to be used with MinGW, compile Boost with the gcc toolset. You will have to choose an installation directory for Boost, which WILL NOT be the same directory where you extracted the files earlier. In my case, I used C:\boost. For this, run the command:
      b2 install --prefix=C:\boost toolset=gcc

      Now go read a book or work on something else because this will take a while.

Now, if the installation worked with just warnings, it is time to run a code example from Boost’s website that, or course, uses the Boost library. Create a new project called “reveillon” and add a source file to it called “days_between_new_years.cpp” following the steps from the “Creating a new project” section. there is no need to use the template this time.

You should now have a blank source file in front of you. If not, delete any text/comments/codes in the file so that the file is blank. Now, copy and paste the following code, from Boost’s example, into your file.

 /* Provides a simple example of using a date_generator, and simple
   * mathematical operatorations, to calculate the days since
   * New Years day of this year, and days until next New Years day.
   *
   * Expected results:
   * Adding together both durations will produce 366 (365 in a leap year).
   */
  #include <iostream>
  #include "boost/date_time/gregorian/gregorian.hpp"

  int
  main()
  {
    
    using namespace boost::gregorian;

    date today = day_clock::local_day();
    partial_date new_years_day(1,Jan);
    //Subtract two dates to get a duration
    days days_since_year_start = today - new_years_day.get_date(today.year());
    std::cout << "Days since Jan 1: " << days_since_year_start.days()
              << std::endl;
    
    days days_until_year_start = new_years_day.get_date(today.year()+1) - today;
    std::cout << "Days until next Jan 1: " << days_until_year_start.days()
              << std::endl;
    return 0;
  };

Note that line 9 (“#include “boost/date_time/gregorian/gregorian.hpp””) is what tells your code what exactly is being used from Boost in your code. Line 15 (“using namespace boost::gregorian;”) saves you from having to type boost::gregorian every time you want to use one of its functions.

However, the project will still not compile in Eclipse because Eclipse still does not know where to look for the Boost library. This will require a couple of simple steps:

  1. Right click on the project (reveillon), under the Project Explorer side window, then click on Properties. Under C/C++ Build->Settings, click on Includes under GCC C++ Compiler. On the right there should be two blank boxes, the top one called Include paths (-I) and the other called Include files (-include). Under Include paths (top one), add the path “C:\boost\include\boost-1_58” (note that this path must reflect the path where you installed Boost as well as which version of Boost you have). This is where the compiler will look for the header file specified in the code with the #include statement.
  2. The compiled library files themselves must be included through the linker. This step is necessary only if you are using a compiled library. For this, on the same window, click on Libraries under MinGW C++ Linker. Add the path to the Boost libraries folder to the Library search path (-L) (bottom box). this path will be “C:\boost\lib” (again, if you installed Boost in a different folder your path will be slightly different). Now the actual compiled library must be added to the Libraries (-i) (top box). First, we need to figure out the name of the compiled library file used in the code. In this case, it is the file “libboost_date_time-mgw51-mt-d-1_58.a”. Therefore, add boost_date_time-mgw51-mt-d-1_58 (no lib prefix, no .a postfix, and be sure to match the name of your file) to Libraries (-i). Click Ok and Ok again.

Now compile the code by clicking on the hammer button and run the rode by clicking on the play button. Below is a screenshot reflecting both steps above as well as the expected output after running the program.

configuring_library

That’s it. After your model is in a good shape and it is time to run it with Borg (or other optimization algorithm), just change your “int main()” to a function with your model’s name and the right Borg’s arguments, add the standard Borg main, and change the makefile accordingly. Details on how to do all this for Borg will be explained in a future post.

How to set up MinGW for the first time

I was quite surprised that no one on the internet has written a simple list of what to do to get a code compiled with MinGW before.  Seems like you have to have 3 PhDs in computer science to read the directions (or maybe I’m just having a bad day).  Nonetheless, we’re here to help.

By the way, you may be asking “What is MinGW?” It is a port of the GNU compilers on Windows (the GNU compilers being the ones that are used on things like Linux and the computing clusters).  Its website is here.  “Wait a sec, why would we want to use MinGW if we already have Cygwin?  Doesn’t it do the same thing?”  Yes.  But, sometimes things won’t work on Cygwin.   Also, I think MinGW is a lot smaller and lighter weight than Cygwin so if you are limited in resources that’s another reason.

Anyway, here goes:

  1. Go to the MinGW website: http://www.mingw.org/.

  2. Click Downloads, and select ‘mingw-get-setup.exe.’

  3. This is an installer that will grab all the proper packages for you.  Make sure to keep the installation directory the same as default: ‘C:\MinGW\’.  Once you click through the set of initial prompts, you will see an install manager.  That install manager has a set of checkboxes, that ask you if you want gfortran, g++, etc.  Right click on the check boxes and select ‘Mark for Installation.’

  4. In the program, under the Installation menu, select ‘Apply Changes’

  5. Wait for everything to download and install, and follow the instructions.  After you are done, it won’t tell you anything, you should just trust that it has completed.

  6. Note that there is a utility called MINSYS that is installed with MinGW.  What that is, is kind of like ‘Cygwin Lite’.  It is a small set of linux commands and a shell, that you can use to compile programs.  We aren’t going to cover MINSYS here but, this is a set of instructions for how to use it.  But what we want to do, is compile programs in the native DOS command window of Windows.  So we need to do a few more things.

  7. Next we need to set the PATH of windows to know where MinGW is.  Why?  Well you want to open a command window in any directory in Windows, and type ‘g++’ and have the computer know what it is you’re talking about. For Windows XP – Windows 7 users, check out instructions here.  We are using Windows 8, so we can use the search functionality.  If you type ‘environment’ in the Windows search box, you’ll see a link for ‘Set System Environment Variables’. Click it.

  8. It brings you to a window that is titled ‘System Properties’.  Click the button that says ‘Environment variables…’  In that window, in the second box, you can scroll down and see a variable called Path.  It should start with ‘C:\windows\system32;C:\windows;’  Highlight Path and click Edit…

  9. At the very end of the list, type a ; (without a space) and ‘C:\MinGW\bin’  So your path should look like: ‘C:\windows\system32;C:\windows;[otherstuff];C:\MinGW\bin

  10. Click OK three times, to get out of all of the windows.

  11. This step is very important!  Restart your computer, otherwise the Path settings won’t take.

  12. Now, after you are restarted, get to the command line by typing ‘cmd’ in a search box.  A black, old-timey window will pop up.  If you type the command: ‘g++’ , it should tell you “g++: fatal error: no input files”  This means g++ is installed, and it is on the path correctly, and it (ostensibly) works.

  13. You will likely need an additional command instead of just the vanilla ‘g++’ and ‘gfortran’  If you are using a Makefile, you need an additional utility.  On Linux this is called ‘make’, but here it’s called something different: mingw32-make.  Thanks to this forum post for this (and other helpful) hint(s)!

You should be good to go.  Now, you have a minimalistic way to compile stuff that is supposed to work using GNU compilers (on Unix and the clusters) on Windows!  As usual, comments questions and concerns should be posted below.

Installing IPython

Intro

If you were at yesterday’s meeting, you’ve seen my enthusiasm for the ipython HTML notebook. This is a short post on how to get it set up.

Windows

iPython

Download the zip file from the iPython release archive. Pick the biggest release version number. Unzip it. Do

python setup.py install

Watch it complain about how you don’t have setuptools. Install setuptools as below and try again.

Setuptools

If you don’t have Python setuptools yet, go get it from PyPI, the Python Package Index.

Tornado

Now that you have setuptools:

python -measy_install tornado

PyZMQ

python -measy_install pyzmq

Linux (but not the cluster)

On Fedora, sudo yum install ipython. Probably sudo apt-get install ipython on Ubuntu, but let me know in the comments if I’m wrong about that and I’ll update the post. You might also need to install tornado and pyzmq, but I don’t recall having to do this. (I did my Fedora install a while ago.)

Starting the iPython HTML Notebook

iPython notebook --pylab=inline

A web browser should pop up. Click on “new notebook.”

Virtual Machines for Remote Code Development

Setting up a Virtual Machine [VM] for Remote Code Development

Many times you’ll be asked to develop applications on remote machines.  Generally these machines are running some flavor of Linux or Unix (*nix systems).  Often, this can be quite complicated for those who are unfamiliar with using command lines or the “vi” editor.  This guide will get you started using a virtual machine to run a Linux operating system on your Window’s PC, and will help alleviate some of the headache associated with remote development.

I’m suggesting the use of a VM for remote development as opposed to separate SSH and X-Server forwarding software such as Cygwin because the VM gives you access to a lot of the software and features of the remote machines on your local machine.  Even things like LaTeX become readily available.  I’m suggesting setting up a local development area because once you’ve “cut your chops” on remote development, you’ll appreciate being able to rapidly develop code locally and then push updates to the remote machines for ‘production’ runs.

This guide will help you get up an running with the VirtualBox VM, with a version of CentOS (a popular flavor of Linux).  CentOS comes with software packages which are directed at software development, such as Eclipse, and contains features available on large cluster systems.  You’ll even be able to install openmpi, and be able to program and test parallel applications, if you so choose.

Installing VirtualBox

VirtualBox is a pretty well-supported, open-source piece of software.  The homepage is located at www.virtualbox.org, and contains links to installers as well as users guides and documentation.  You’ll need to download the Host Software as well as a Guest OS.  The Host software, (VirtualBox) runs the virtual machine (the Guest).  Just like a standalone computer, you’ll need an OS to run on the Guest.  Here’s a quick link to their download page:

https://www.virtualbox.org/wiki/Downloads

You’ll want to head over there and download the latest version of VirtualBox for Windows Hosts (x86/amd64).  This is the VM software that will manage your virtual machines.  At the time of this writing, VirtualBox is at version 4.1.8.  They have a pretty solid install guide in their manual, located here:

https://www.virtualbox.org/manual/UserManual.html

Go ahead and install VirtualBox, and configure a new virtual machine.  A good video guide (though slightly dated) is provided below.  When they get to the step where they determine the size of the hard drive, they use dynamically-sized storage.  You’ll want to change it to fixed-size; around 20 gigabytes or more if you can handle it.  Our settings will be for Red Hat (the core Linux within CentOS).  We’ll get to installing an OS on the virtual machine shortly.

Installing an OS to the VM

Congratulations! You now have a computer running within a computer.  This is where things may become complicated if you’ve never installed an OS before.  It’s become much easier than in the past, and there’s a pretty good video posted on YouTube with an example walkthrough.  You’ll want to make sure your computer is connected to the internet before you start the install.  Virtualbox will automatically connect to the net, and the OS installation will grab some packages from the net if you tell it to.  Around 3:15 in the video, you’ll see an example of the package selection screen.  You’ll want to select the “Software Development Workstation” option.

Installing Additional Software: VirtualBox Guest Addons

Now that the OS is up and running, you want to be able to fully use all the fancy features and graphics packages of VirtualBox to maximize its performance and ease of use.  This is done through the VirtualBox Guest Addons.  It will allow you to “fullscreen” the VM, as well as some other nifty tricks.  Technically this is optional, but it really should be required.  A walkthrough is provided byVirtualBox, and can be found here:

http://www.virtualbox.org/manual/ch04.html

Simply follow the provided instructions for Guest Additions for Linux. Since we’ve installed CentOS, we’re using a variant of Red Hat Enterprise Linux (RHEL), so scroll to the specific instructions for CentOS, Red Hat Enterprise Linux and Oracle Enterprise Linux.  A video walkthrough is provided below:

Configuring Remote Display

This is where things get easy.  Since you’re running Linux in the VM, you’re basically already set up to push GUIs and windows back to your local machine from the remote one.  All it takes is the command:

ssh -Y <username>@<remote-system>

The -Y option for ssh allows the remote system to forward X11 data (GUIs, windows) back to your machine.  Pretty easy, right?  Log in to a machine and type xterm to push a remote terminal window back through your ssh connection to test it.

Discussion

First, I’d like to note that a virtual machine is useful for running multiple OS for various reasons, however you take a hit to performance due to the virtualization layer.  Most modern computers are multi-core, which allows your primary OS to offload the virtualization to one core, and run calculations with the other.  This alleviates some of the performance hits, but does not remove it completely.  Some newer Intel systems can use specialized hardware to improve performance and even use the 64-bit (x86_64) versions of OS.  Such optimizations are beyond the scope of this guide, but if there’s enough demand I’ll write a more in-depth version including it.

Installing Additional (Optional) Software: Netbeans

While the Software Development Package comes with an Integrated Development Environment (IDE) called Eclipse, my personal IDE-du-jour is Netbeans.  Eclipse is more versatile when it comes to languages, but if you’re a C/C++ developer, Netbeans is also pretty convenient.  It is a little simpler to configure for remote development, and is easier to switch between local and remote.  If you wish to familiarize yourself with Eclipse, a good resource can be found here and at the Eclipse website, here.

From inside your remote machine, head over to netbeans.org and download the install script for the “All” version.  Remember where you download it, as you’ll have to navigate to the script on the command line. Installation instructions can be found here, but remember to perform these commands as “su” using the sudo command:

sudo chmod +x <installer file name> sudo ./<installer file name> 

During the installation, agree to the licenses, and if you’d like feel free to install the Glassfish server and Apache Tomcat packages.  If you don’t know what they are, you probably don’t need them, unless you’re deep into open-source development and web environments for Java.

Once installed, you’ll be able to find the software in the Applications->Programming menu.

Installing Additional (Optional) Software: OpenMPI

You can do this one of two ways: through the Add Software GUI, just search for openmpi and it’ll come up in the list of packages.

or on the command line, by running:

sudo yum install openmpi openmpi-devel