UnitC++ on SourceForge

My latest project, UnitC++ , is now live on SourceForge. Check it out here


Humour in the C++ standard

It’s nice to see that the C++ standard, while mostly dry, has a little humour in it. There is a limerick in section 14.7.3, 7. It goes like this;

When writing a specialization,
be careful about its location;
or to make it compile will be such a trial
as to kindle its self-immolation.

And according to Mostly Buggy in version C++0x FCD there was an amusing footnote in Section 29 Atomic operations library

29.1 General [atomics.general]
1 This Clause describes components for fine-grained atomic access. This access is provided via operations on atomic objects.341
341) Atomic objects are neither active nor radioactive.

But sadly in my copy (ISO IEC 14882) this was not included. It must have been taken out before the official standard was released.

There are according to Michael Wong two limericks in the standard, but I couldn’t find the second one (in the doucment, or on the internet).



This post is an introduction to a library I have written, UnitC++.

UnitC++ is a modern, light weight, header-only c++ library for making unit testing easy. The intention of this library is to make it really easy to test c++ code in a portable way.

How to use UnitC++

How to get UnitC++

UnitC++ is stored in a mercurial repository. The best way to get it is to clone it onto local disk. Like so.

cd ~
hg clone https://davidcorne@bitbucket.org/davidcorne/unitcpp

You can also download/clone it from GitHub at https://github.com/davidcorne/UnitCpp

How to include UnitC++ in your project

As a header-only library this step should be easy to accomplish. However While how you do this will vary depending on your build process, it will be straightforward. As this is a header-only library all you need to do is add the repository path to the compiler include line. Here are two examples of how that is done.

From command line

Compiling from the command line you add the argument -I $(path_to_unitc++). This works for g++/clang/cl from the command line. This can also be added to the compiler arguments in a makefile.

From Visual Studio

in Visual Studio you go to Project Properties -> C/C++ -> Additional Include Directories, and browse to $(path_to_unitc++).

How to write a unit test using UnitC++

Writing a test

The first thing to do is include . This is the header which will bring in everything you need.

Then you need to declare you are writing a test by writing TEST(goup_name, test_name). This works like declaring a function, so a set of tests for a class called MyString will look something like this.

#include <UnitCpp/Test.h>

TEST(MyString, length_test)

TEST(MyString, validity_test)

Note: the pattern here is to write several tests for a class with the class as the group_name and what you are testing as the test_name in the TEST macro.

Now you are ready to write the test code. UnitC++ provided some helpful macros for writing tests. Here is a list of them.


So here is a filled out version of the above example of a test.

#include <UnitCpp/Test.h>

TEST(MyString, length_test)
  MyString str("This is a string");
  TEST_EQUAL(str.length(), 16);
  TEST_NOT_EQUAL(str.length(), 17);
  TEST_LESS_THAN(str.length(), 20);
  TEST_MORE_THAN(str.length(), 10);
  TEST_APPROX_EQUAL(str.length(), 15, 1.1); // test the length is within 1.1 of 15

TEST(MyString, validity_test)
  MyString invalid_string;

  MyString valid_string("");

  TEST_THROWS([&](){invalid_string.length();}, MyString::InvalidStringException);


This is obviously a contrived example, there are several tests checking the same thing. i.e. that the length of "This is a string" is 16. However it is an example of how the macros are used.

Note the use of TEST_THROWS, it is for testing that a certain exception was thrown. It takes a function to call, the exception which should be thrown and the arguments to the function. Note the use of a lambda function, this is because TEST_THROWS is expecting a function and you want to call a member function.

In each TEST you can use functions from TestCase. This means for example, you can call test_equal(1, some_function()) if you want the values to be compared as doubless not ints.

Running the tests

So you’ve written a nice set of tests and now you want to run them. This is done with the TestRegister class. This is a singleton that has registered all of the tests you’ve declared with the TEST macro. These are run in the following way.

#include <UnitCpp/TestRegister.h>

int main()
  return UnitCpp::TestRegister::test_register().run_tests();

As long as the code with the tests in is linked into the executable TestRegister::test_register().run_tests() will run the tests.

You can also call TestRegister::test_register().run_tests("group_name") to run all the tests in a specific group.

Working examples

In the Example folder there is a working example for a further demonstration of some of the capabilities of UnitC++.

Frequently Asked Questions

UnitC++ doesn’t work with my compiler!

Ok, this isn’t actually a commonly asked question. But, if your compiler doesn’t work with UnitC++ please let me know! I will fix this as soon as I can. See _How do I report an issue or request a feature_ for how to let me know, thanks.

How do I request a feature or report an issue

I am always happy to take a look at an improvement or fix a bug, you just have to let me know about it. The best way to do this is file an issue on my issue tracker. This is located here don’t be shy, I’m not going to snap at anyone.

Do you use this?

I made UnitC++ for my personal use. This means that I use it whenever I need to test anything.

How is UnitC++ tested?

It’s tested using UnitC++ of course! I run continuous integration using drone.io. I currently test it with g++, clang and cl. On drone.io I test g++ and clang and I test/develop with g++ and cl on my windows machine using cygwin. The current state of the drone.io build is Build Status.

How does it work?

Each TEST does 3 things:

  1. It defines a class derived from TestCase.
  2. It makes a global instance of this class.
  3. It lets you provide the body of the overriden function run().

The reason a global object is declared is to call the constructor. In the constructor of TestCase it registers itself so TestRegister knows which tests to run. This is how as long as the objects are linked against, TestRegister::test_register().run_tests() will run them all.

You say this is a modern library, why are there so many preprocessor macros?

This is because unfortunately macros are the best way of doing some things. Macros are used for 2 reasons in UnitC++.

  1. For judging compiler support. For the TEST_THROWS functionality we use variadic templates, this was not supported by visual studio until 2013. As pre-2013 visual studio compilers are in very wide use, we decided to include this functionality for those with compiler support, and to not break the build of those without.
  2. For generating good error messages in tests. Compare the following message; Fail: These arguments should be equal and Fail: "Maths::sqrt(4.0) should equal 2." utest_Maths.cpp:8. I know I prefer the second one, and getting the line of code, file name and line number cannot be done without macros.

Contributing to UnitC++

The GitHub site is a mirror of the mercurial repository. So you should use mercurial and bitbucket. Send me a pull request at https://davidcorne@bitbucket.org/davidcorne/unitcpp and I’ll get back to you.


Functional Data Structures in C++: Lists

David Corne:

Great article by Bartosz Milewski. I’m always interested in applying different paradigms to C++. Here is my attempt at this.

Originally posted on   Bartosz Milewski's Programming Cafe:

“Data structures in functional languages are immutable.”

What?! How can you write programs if you can’t mutate data? To an imperative programmer this sounds like anathema. “Are you telling me that I can’t change a value stored in a vector, delete a node in a tree, or push an element on a stack?” Well, yes and no. It’s all a matter of interpretation. When you give me a list and I give you back the same list with one more element, have I modified it or have I constructed a brand new list with the same elements plus one more?

Why would you care? Actually, you might care if you are still holding on to your original list. Has that list changed? In a functional language, the original data structure will remain unmodified! The version from before the modification persists — hence such data structures are called persistent (it has…

View original 4,199 more words


Using ediff with Version Control

This is just a quick note about a nice emacs feature.

If you develop with emacs, you may have heard of/used ediff. This is a very handy diff program which runs inside emacs. We use this with a custom hook at work to work with our version control system. I found out that it works nicely with more standard version control systems as well.

The main way to use ediff is the command


This lets you choose two buffers to diff. To do this for different revisions of a file you can use the command


This will ask for which file you want to view revisions of (default, the current buffer), and the two revisions to compare (default latest revision and the current state). The you will have the file you asked for loaded in the two revisions you asked for.

Using mercurial personally I find this more informative than the output from hg diff in complicated cases. I believe this works for any version control system recognised by emacs, e.g. mercurial git and subversion.


C++ Digraphs

This is not as you might think, an article about implementing directed graphs in C++. The digraphs I am writing about are sequences of characters which act as a stand in for other characters. Digraphs and trigraphs exist in many languages, but I will be focusing on C++. The difference between digraphs and trigraphs is simple the number of characters, a digraph is 2 characters and a trigraph is 3 characters.

Digraphs are part of the language because in the past special characters were hard to input. This was generally because they were not on the keyboard, but in a few cases, they were not even in the code page!

So what use is this now, when modern keyboards have all the symbols we could want and we can use different encodings in source files?

Here is a screenshot of the C++ standard where it defines the allowed digraphs.

Digraphs in C++ Standard

C++ standard digraphs

The first column are backwards compatible digraphs for C. The next two columns are rather interesting.

For example. If you write the word or in a C++ source file, the compiler will replace that with ||. This means that the following code compiles and works.

int main() {
  bool a = false;
  bool b = true;
  std::cout << "a or b == " << (a or b) << std::endl;
  return 0;

Not only will this work for built in types, this works for user defined operators too. This is because the compiler simply substitutes the symbols.

Here is an example class and calling code which uses all the C++ digraphs.


This is just a stub class which defines a lot of operators which do nothing.

class Example {

  // logic operators
  bool operator&&(const Example& t) {
    return true;
  bool operator||(const Example& t) {
    return true;
  bool operator!() {
    return true;
  // bitwise operators
  bool operator&(const Example& t) {
    return true;
  bool operator|(const Example& t) {
    return true;
  bool operator^(const Example& t) {
    return true;
  bool operator~() {
    return true;
  // logic equals operators
  Example operator&=(const Example& t) {
    return t;
  Example operator|=(const Example& t) {
    return t;
  Example operator^=(const Example& t) {
    return t;
  Example operator!=(const Example& t) {
    return t;

Calling Code

int main() {
  bool a = true;
  bool b = true;
  if (a and b) {
    cout << "\"and\" is an operator." << endl;
  if (false or b) {
    cout << "\"or\" is also an operator." << endl;
  if (not false) {
    cout << "\"not\" is also an operator." << endl;

  Example t_1, t_2;
  if (t_1 and t_2) {
    cout << "\"and\" even works for classes" << endl;
  if (t_1 or t_2) {
    cout << "\"or\" even works for classes" << endl;
  if (not t_1) {
    cout << "\"and\" even works for classes" << endl;
  if (t_1 bitand t_2) {
    cout << "\"bitand\" also works for classes" << endl;
  if (t_1 bitor t_2) {
    cout << "\"bitor\" even works for classes" << endl;
  if (compl t_1) {
    cout << "\"compl\" even works for classes" << endl;
  if (t_1 xor t_2) {
    cout << "\"xor\" even works for classes" << endl;
  t_1 and_eq t_2;
  cout << "\"and_eq\" even works for classes" << endl;
  t_1 or_eq t_2;
  cout << "\"or_eq\" even works for classes" << endl;
  t_1 xor_eq t_2;
  cout << "\"xor_eq\" even works for classes" << endl;

  return 0;

This gives the output;

"and" is an operator.
"or" is also an operator.
"not" is also an operator.
"and" even works for classes
"or" even works for classes
"and" even works for classes
"bitand" also works for classes
"bitor" even works for classes
"compl" even works for classes
"xor" even works for classes
"and_eq" even works for classes
"or_eq" even works for classes
"xor_eq" even works for classes

This file can be found here.

This is an interesting feature, but is it useful?

I think it is, I think that the code;

if (not fail and ok) {
  // ...

Is more readable than;

if (!fail && ok) {
  // ...

However just because these are defined in the standard does not mean they can be used. These are largely considered a legacy part of the standard and there is limited support for it.

In particular Microsoft’s C++ compiler will not compile it. Both clang and g++ will compile it however, so if you are compiling using either of these you can use this nice feature.

Thanks for reading.


Keeping History Using the cd Command

If you use shell scripting a lot from the command line, this will probably improve your experience of it. This is for users of linux/mac command line or of cygwin on windows. Anywhere you can use the bash cd command.

Firstly (if you didn’t know) cd remembers the last directory you went to. To access this use;

cd -

This will change to the previous directory you were in. If you want to supercharge this you can add the following to your .bashrc/.profile/… customization file.

# petar marinov, http:/geocities.com/h2428, this is public domain
cd_func ()
  local x2 the_new_dir adir index
  local -i cnt

  if [[ $1 ==  "--" ]]; then
    dirs -v
    return 0

  [[ -z $1 ]] && the_new_dir=$HOME

  if [[ ${the_new_dir:0:1} == '-' ]]; then
    # Extract dir N from dirs
    [[ -z $index ]] && index=1
    adir=$(dirs +$index)
    [[ -z $adir ]] && return 1

  # '~' has to be substituted by ${HOME}
  [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir="${HOME}${the_new_dir:1}"

  # Now change to the new dir and add to the top of the stack
  pushd "${the_new_dir}" > /dev/null
  [[ $? -ne 0 ]] && return 1

  # Trim down everything beyond 11th entry
  popd -n +11 2>/dev/null 1>/dev/null

  # Remove any other occurence of this dir, skipping the top of the stack
  for ((cnt=1; cnt <= 10; cnt++)); do
    x2=$(dirs +${cnt} 2>/dev/null)
    [[ $? -ne 0 ]] && return 0
    [[ ${x2:0:1} == '~' ]] && x2="${HOME}${x2:1}"
    if [[ "${x2}" == "${the_new_dir}" ]]; then
      popd -n +$cnt 2>/dev/null 1>/dev/null

  return 0

alias cd=cd_func

This means that you can keep a history of the past 10 directories which you have visited and change between them.

To access this list type

cd --

Which will print a list like.

0  /e/projects/dgc/or14126h_3
1  /e/projects/dgc/or14126h_3/orthotics.dev
2  /c/Users/dgc/Dropbox/Coding
3  /e/projects/dgc
4  /e/projects/dgc/or14126h_2
5  /e/devdisk/dcm/configs
6  /e/devdisk/dcm
7  /e/devdisk
8  /e

And then

cd -5

will take you to entry 5 in the list.

To be clear I did not write this, I found it in the default cygwin .bashrc. The author of this was Petar Marinov.

I have found this very helpful, particularly when using a new python module. This is the process;

  • I would be in my working area
  • download it from pypi
  • cd to my download area
  • untar it
  • cd into it
  • run python setup.py install
  • then want to go back but cd – would get me to my download area.

This function removes that minor inconvenience and I have found it very useful.

Thanks for reading.


Get every new post delivered to your Inbox.

Join 152 other followers