Project Structure for Projects in Qt Creator with Unit Tests


For this post I will be proposing a project structure in Qt Creator that allows you to have your unit tests project with your main project.


If you think this post looks familiar, you have probably gone through a similar post from Svenn-Arne Dragly. This project is actually a simpler fork of his, so credits to him.

Why fork out from Dragly’s project structure? (you can skip to the next part if you want.)

I had to build out a library file – this is a bit of a hassle to me. In addition the example in github ( didn’t work either:

LNK1104: cannot open file 'myapp.lib'.

It’s because I’m using the MSVC2013 compiler and it only builds out a *.dll and forgot a *.lib. Turns out I have to add __declspec( dllexport ) as so:

class MyClass {
     __declspec( dllexport )  double addition(double a, double b);

Even so it still asks for the *.lib file, despite it already being built. I had to explicitly add the path to the external library, and then place the compiled *.dll in the same directory as the executable. I guess, if I specify a common build directory and have it look for the lib file there it would work… but think about this: __declspec( dllexport ) is microsoft specific. If I run the same code in linux it spits out an error. I could use some macros to check for what compiler is being used, but it’s a hassle (to me, at least).

So if you only intend to develop using a particular compiler that’s fine. I just figured I wanted something more straightforward.

Project Structure

The approach I came up with involves compiling some/most of your code twice, but it was what I stick to in the end for a test project I was working on (Click here to download an empty template) :

Project Directory:
 ├───app -> source code
 │       AbstractGroup.hpp
 │       ActiveSelection.cpp
 │       ActiveSelection.hpp
 │       Canvas.cpp
 |       ...
 ├───build -> build directory
 │       DrawingApp.exe
 ├───lib -> libraries
 │       catch.hpp
 └───tests -> test project, which you only add files from the 'app' folder that you want to test
         TestMain.cpp -> DO NOT call this main.cpp! It will clash with your main.cpp in the 'app' folder, even though they are in separate directories.

You can see a real life example in my github project: – I will be referring to this project so do keep a tab open.

It will look something like this in Qt creator:

2015-05-30 14_13_55-defaults.pri - MyProject - Qt Creator

This might be a hassle for some, because you would have to add the source files into the unit test project every time you created a new class. Otherwise the unit test project will fail to build and you’d likely confuse it to your actual project not building.

But that was just because I wasn’t really doing TDD. I created the source files before I write the unit tests. Well, it’s a drawing app; I can’t unit test drawing capabilities right?

Loose Coupling, Tight Coupling

After initial frustrations of using this structure, I realized doing it this way does disciplines a programmer to think about coupling. After a while it had me asked questions like “If I just want to test object A, should I need to also depend on object B and C? Can object A be isolated and used separately?”.

Great software design meant loose coupling; only when necessary should objects be bundled together. Otherwise they should be able to be packaged, isolated, reused, and unit tested separately.

This is why the file contains significantly less files compared to

Calling headers in different directories

Notice, that for example in the DrawingApp project, that a fileio/JsonFileReader.hpp is able to call interfaces/IFileReader.hpp by just

#include "IFileReader.hpp"

This isn’t default behaviour as in codeblocks, I had to manually configure this in the project file for both and

 $$PWD \
 interfaces \
 commands \
 tools \
 shapes \

Tedious maybe, but a small inconvenience to me. I wasn’t sure if Qt Creator has a setting to make this default behaviour, but this is what I can come up with.

A Note on Catch

This single header unit test framework is too easy and convenient not to use. The TestMain.cpp simply needs to contain


#include "catch.hpp"

and then you can start adding separate test *.cpp files for each class (or however you want to structure your tests).

If you haven’t tried it out I highly recommend you do.


Think there can be a better way? I’m open to ideas.

You can download an empty template project from here: Click here to download an empty template.



Using std::unique_ptr as a class member (C++11)


For this post I’m going to go through some of the gotchas most people might face when using unique_ptr as a class member (most examples out there only show unique_ptr as a local variable), all accompanied by examples. I will also compare it with shared_ptr.


I’m assuming you know your way round classic/naked pointers, basic memory management and object construction and destruction.


Unique pointers is type of smart pointer in the C++11 standard that uses the concept of ownership, which meant that only 1 pointer can point to 1 resource (ergo ‘owns’ the resource). In other words only a single pointer is responsible for the destruction of its resource, hence the term ‘unique’.

Theories aside, let’s see some code! To see the source code of the files in this post, just click the link – it will point to a github gist (For example, click Point.hpp below).

Getting Started

In this scenario we’ll be managing a class Point (Point.hpp) from a manager class PointMan. Then add shared_and_unique.cpp to the same directory get started.

So we start with our unique pointer q:

Point::UPtr q;

UPtr here refers to a typedef std::unique_ptr<Point>, you can actually use these interchangeably. Why do Point::UPtr? Because other people do this. And it looks more concise. In fact, if you ever intend to use smart pointers to manage a class, you should add a typedef there.

Now, notice that the unique_ptr p is initialized at the constructor:

PointMan() : q(new Point("q")) {
    q->set(6, 12);
    // ...

well, what if you don’t want to initialize at the constructor? You do this:

r = Point::UPtr(new Point("r"));
r->set(r_x, r_y);

Here is the output of unique_and_shared.cpp:


Ownership Transfering

Moving on to the next example: unique_container.cpp

How does one transfers a unique pointer to another unique pointer? An example is when you have created a point:

Point::UPtr temp(new Point("element-" + ss.str()));
temp->set(i, i*2);

And now you want to transfer this temp Point to a container of unique pointers. Why? Currently the unique pointer is being initialized in a for loop. Exiting or restarting the loop will destroy the resource. That is why the life management of the object needs to be passed to a variable in the class scope. However, doing this:

container[i] = temp;

will result in a compile time error:

unique_container.cpp:16:17: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Point; _Dp = std::default_delete<Point>]’

what does it mean? You can’t use assignment operator from one unique pointer to another unique pointer. Why is this so? Because unique pointers are designed in such a way such that only one pointer can own one resource. However, ownership can be transfered. The following is valid:

container[i] = std::move(temp);

What happens now is that the job of managing the life time of the object is now passed down to the container. So now temp pointer doesn’t point to anything:

assert(temp == nullptr);

Of course, if you don’t want to create temporary variables and move them, you could simply initialize the array element directly:

container[i] = Point::UPtr(new Point("element-" + ss.str()));
container[i]->set(i, i*2);

Non-owning Pointers

Now comes a tricky problem: say there is an element my container of points that I want to designate as the location of the current player on a game board. I need a convenient means to access this particular point in the container. I can’t store this Point as a unique pointer as only one unique pointer can point to one resource. How can I go about doing so?

Well, what you can do is save the index of that container and use it accordingly:

container[player_idx]->set(45, 12);

but it’s rather tedious, messy, and not very expressive. And what about data structures that are not indexed? This creates an overhead simply to get to the resource. What we can do is use a non-owning pointer. Non-owning pointers are classic pointers that do what you would expect normal pointers would do, except they should not manage the life time of the object.

Point *mainPoint;

You assign a raw pointer the resource by using the get() method:

mainPoint = container[1].get();

Now here’s where you need to be careful: do not delete this pointer!

delete mainPoint; // don't do this! no no no!

Your compiler won’t stop you from doing so, but you can cause some really insidious bugs to your program. mainPoint should only serve as a pointer where you can pass around to access the object in the heap. By no reason should you try to manipulate the life time of the resource via this pointer.

But anyhow, I was curious what would happen:


Data corruption! Wohoo! 😀

VS Shared Pointers

So to conclude, here’s the same Pointer manager class, but now using shared pointers: shared_container.cpp

So it’s really a lot easier to read, and more consistent. In fact, Objective C only uses reference counting to handle heap memory. SFGUI, a GUI toolkit built for SFML, forces you to use shared pointers to create GUI components. Seems like shared pointers is one size fits all right? I would think so.

But of course, people would debate that unique pointers perform better than shared pointers, and that shared pointers should be only used as a last resort.

Personally? Shared pointers for the win, man.

So leave a comment if you feel this article could elaborate on certain things or whatever. Bye for now! 😀

Building ASSIMP 3.1.1 with MinGW 4.8

As of this writing I’m using CMake 3.0.0, Windows 8.1, MinGW 4.8.1 and Assimp 3.1.1.

[Precompiled binaries with inlude headers are attached at the end of this post for your convenience. ]

I’m assuming you’re stuck in cmake GUI after selecting MinGW as your native compiler, and that you have MinGW in your environment paths.

If you want to build Assimp Viewer, have ASSIMP_BUILD_ASSIMP_TOOLS checked and you’ll need to install directX SDK (June 2010).  If you have “S1023” error when you install the DirectX SDK go to

Set CMAKE_BUILD_TYPE to “release” (without the double quotes). If you didn’t see this option, you’ll have to check “Advanced” (next to Add entry). If you didn’t do this, your library size would be pretty big, if it even builds finish. For me it got stuck at 42% – building IFCReaderGen.cpp.obj because of some error of the file size being too big and having too many sections.

Now you should be able to configure and generate with zero errors. cd to the build directory and run


The compiled libraries will be in <cmake-build-directory>/code

If you have problems building stuffs from unit.dir, just uncheck ASSIMP_BUILD_TESTS. Though, by then both the assimp library and the viewer would have been built.

Just so you know, the compiled library is many times bigger than when it was compiled with VS2013.

So here is the precompiled binaries, both dynamic and static. Debug builds can’t be built as explained earlier:

Download link [MediaFire] : (7.16Mb)

Auto-formatting source code using AStyle

Today I talk about how to get AStyle 2.04 the awesome code beautifier working with Qt Creator 3.1, and towards the end share my configuration settings (C++).


I have a particularly strange habit to code: I can’t stand it if it doesn’t look pretty. I make a fuss about formatting, on whether code is readable and properly formatted by consistent and standard code conventions. In short, messy code is disgusting to me.

I doubt I’m the only one like this (:

For awhile now I’ve been manually formatting the code, little seemingly insignificant stuff point of adding spaces between operators and removing spaces around parenthesis, until I realize how it was actually kinda unproductive.

Enter AStyle

I setup Qt Creator via this link. Apparently Qt Creator 3.1 already has beautifier just setting around, but disabled for some reason. You then need to download AStyle and set the exe accordingly.

Then… after that I started wandering around the web wondering where to get a predefined set of formatting options for it. It was actually quite hard to find what I was looking for, truth be told. In the end I just look up the documentation and make it work for me. It wasn’t too bad; was actually kinda fun seeing the code just fixed up itself.

So here is my self-defined style (C++):


My only gripe was that the only way to format the code I have to go through the menu:

Tools > Beautifier > Artistic Style > Format Current File.

I mean, I wanted to format a dozen files at once. Couldn’t there be a faster way? I can’t assign a keyboard shortcut to this command.

…but I’m glad nonetheless 😀

Troubleshooting SFGUI in shader based OpenGL in SFML

As of this writing I am using SFML 2.1 and SFGUI 0.2.3.

The snippets of code here are part of a commit I made in my personal project OGLMan when getting my OpenGL window to work with SFGUI: see it here.

My goal is simply to get this to render in my SFML OpenGL window:


And I bump to a dozen problems that cause SFGUI to not appear at all. Why? It’s because SFGUI uses OpenGL to draw the GUI!

I assume you are using sf::Window as your OpenGL window, and that the GUI code is inside your subclass:

MyOpenGLWindow::MyOpenGLWindow(sf::VideoMode mode,
                               const sf::String &title,
                               unsigned int style) :
sf::Window(mode, title, style) 
 // bla bla bla...

Before anything begins, first things first. Add the following function call


into your constructor.

Next thing to bear in mind is that you need a sfg::Desktop and sfg::SFGUI object as your private attributes:

sfg::SFGUI sfgui; // you need this
sfg::Desktop desktop; // ...and this
sfg::Label::Ptr test_label;

Now also in the constructor we top on the code to setup the GUI:

auto window = sfg::Window::Create();
window->SetTitle("An amazing title");
test_label = sfg::Label::Create( "Hello I am a window\nthat serves to occupy\nspace");

Then we need to have SFGUI dip its fingers into the event loop:

sf::Event e;
while (this->pollEvent(e)) {
    desktop.HandleEvent(e); // add this.
    switch (e.type) {
        case sf::Event::Closed:
        return true;
// more events...

When drawing the GUI, you have to disable GL_DEPTH_TEST, if you have enabled somewhere in your code (you most likely have). So you need to switch back and forth enabling GL_DEPTH_TEST to render your geometry and disabling it when rendering the GUI.

void MyGLWindow::guiDraw()
    // disable depth test so SFGUI can render

note that the SFGUI object’s Display() method call have to be called BEFORE SFML window’s display().

Also, when using VAO (Vertex Array Object), each time you call a


you must finish it with a


Otherwise you get really strange and notoriously hard to debug problems with your render, and your GUI is no where to be found


Here’s how it should look:


Here’s an example code snippet:

glUniformMatrix4fv(normals_loc, 1,
                       GL_FALSE, &normal_matrix[0][0]);
// bla bla bla...
glDrawElements(DRAW_MODE, indices.size(), GL_UNSIGNED_SHORT, (void*)index_buffer_offset);
glBindVertexArray(0); // don't forget this!

Also, when you use a shader program:


You must nullify it BEFORE you draw any GUI:


So again, you have this switching back and forth thing for every single frame. Note that you don’t have to call glGetUniformLocation again when switching on and off your active shader program.

Lastly, if you have wireframe rendering in your scene, you should know that SFGUI will also be affected. So if you just place


before you render, your GUI is going to look like this:


Those white scratches are suppose to be text. Cool huh? It shows that SFGUI GUI components are really all made of triangles!

So anyhow, if you are rendering wireframe of your 3D geometry, you need to be switching back and forth from wireframe polygon mode and fill polygon mode. Fill mode is as follows:

glPolygonMode(GL_FRONT, GL_FILL);

Yup – that’s all the problems I came across…  Hope this helped somebody; leave a comment if you find other things that needed to be addressed when using OpenGL with SFGUI.

To conclude, here’s SFGUI working happily in my OpenGL window:

2014-08-03 00_20_50-C__Qt_Qt5.3.0_Tools_QtCreator_bin_qtcreator_process_stub.exe