Sunday, May 2, 2010

Putting some Google Goodines in your Code

Adding Protocol Buffers and GTest to your C++ project in Eclipse

(this post is also available as a Google Doc)

Use of Protocol Buffers

Download the package from the Google Code website (we are currently using version 2.2.0) and unpack the tar.gz file in a directory (say, /usr/share/protobuf_2.2.0) and then follow the steps outlined in the INSTALL.TXT file.

NOTE -- you must run the last step as root or installation will fail:

sudo make install

(optionally, run sudo make clean).

Once installed, you will have a bunch of files in your /usr/local/include and /usr/local/lib directories, these matter!

Using Eclipse, you can create a new C++ Project and then have to set up the include directories and add the protobuf.a library -- otherwise your code will not compile/link.
(this is not explained anywhere in the protobuf documentation).

Add the include directory

Right-click on the Project's folder, Properties > Settings: add /usr/local/include in the Directories for the C++ Compiler options:






Add the libraries directory

In the Directories for the C++ Linker options add /usr/local/lib; however, this does not seem to work, if one then adds libprotobuf.a in the box above (Libraries) the Linker will complain that it cannot find the file. Not sure whether this is a bug or "intended behaviour".


Select instead "Miscellaneous" and add into the "Other objects" dialog the full path to libprotobuf.a: /usr/local/lib/libprotobuf.a



Accept (OK) the settings, build the project, profit!


Adding gUnit Tests


This is a very similar procedure to the above: download and install Google Test from the Google Code website, install the code someplace on your disk and then add /usr/local/lib/libgtest.a and /usr/local/lib/libgtest_main.a to the Miscellaneous section in the C++ Linker.

NOTE -- to run the unit tests, your code must NOT have a main() function defined (simply rename it to something else).

Then you can add a prime_test.cc file in your project and run it simply by right-clicking the Project's folder and choosing Run As > Local C/C++ Application; libgtest_main will provide the main() to run the tests.

/* * p3_unittest.cc * * Unit test for Problem 3 * * See p3.cc * * Created on: 21-Dec-2008 * Author: Marco Massenzio (m.massenzio@gmail.com) */

#include <iostream>
#include <gtest/gtest.h>

#include <set>


#include "../common/euler.h"

using namespace euler;

TEST(PrimeTest, IsThree) {
ASSERT_TRUE(isPrime(3));
}

TEST(PrimeTest, IsTen) {
ASSERT_FALSE(isPrime(10));
}



where isPrime() is defined in euler.h/euler.cc as follows:

namespace euler {
// returns true if n is prime
bool isPrime(const long n);
}

No comments:

Post a Comment