tweex[dot]net
My experience using CMake (and a tutorial)

Introduction

For those of you that don’t know CMake is a cross platform build system that allows you to define what you want to build and how, before it goes off and creates the correct build scripts for your particular platform and compiler. It is supposed to help you to simplify your build process when compiling for multiple platforms by just having to maintain a single build script that can generate all other build scripts.

Generally I never had a use for a such a thing since I did all my work on Windows with Visual Studio however when I started doing work I eventually wanted to use on Linux too, I knew I had to look into something. OGRE had started using CMake to generate its build scripts, so I thought I’d look into that. This turned out to be much harder than I expected considering the documentation for CMake seems to range from poor to non-existent and that the examples they link to are either really quick overviews, or really contrived and complicated.

Still I persisted, and with the use of the OGRE CMake files as an example, and with the help of jacmoe and CABAListic I managed to get a CMake file that worked. It was ugly, it was all in one CMakeLists.txt file (which you shouldn’t really do) but at least it managed build two of my libraries on Linux. Of course, I was never able to test if these libraries ran on Linux since I never worked out how to link those libraries against an executable (or even how to recurse into my examples directory so I could attempt to build the examples). After 6 months I figured it was time for me to work out how to use CMake “properly”, I made myself a simple test case that represented what I ultimately needed to do, and then tried to build the CMake script to generate the correct build scripts for it.

Read More

Setting up nForce in Windows 7

I’ve recently installed Windows 7 on my main PC, removing the old Vista install. While doing this I had some issues getting my on-board nVIDIA nForce 6 network drivers working, and from looking around the internet, I am not alone.

The solution that eventually worked for me is as follows:

  1. Shut down your PC and turn it off at the mains for ~20 seconds.
  2. Turn your PC back on and boot into Windows, it should now be able to see and use your nForce network adapters to access the internet, however if you restart Windows you will find that the adapters become disabled again.
  3. To solve this, go to the nVIDIA website and download the correct nForce drivers for your motherboard, and then install them (you will only be able to install the network drivers if Windows is currently able to use the adapters, so if they are disabled, you will need to repeat step 1 before continuing).
  4. Reboot your PC and you should now find that your network adapters are working, and will also continue to work after you restart your PC.
Setting up Redmine on WebFaction

Since this is something I have recently had to do, and found the documentation to be out of date, I though I would share this working solution with you all. This is based on Redmine 0.9.x, and thanks to Sean F from WebFaction support, these instructions are mostly his.

  1. Go to your WebFaction control panel and create a new MySQL database, making a note of the database name and password.
  2. Create a new Rails 2.3.5 application from your control panel, noting the name of the application.
  3. Create a new website to serve the rails application you just created. eg, redmine.domain.com
  4. Login to your server using SSH
  5. Go to your Rails application directory, eg ‘cd ~/webapps/my_redmine_app’ replacing ‘my_redmine_app’ with the name of your actual Rails application.
  6. Run the following commands:
  7. export PATH=$PWD/bin:$PATH
    export GEM_HOME=$PWD/gems
    gem install mysql
    wget http://rubyforge.org/frs/download.php/69449/redmine-0.9.3.tar.gz
    tar zxf redmine-0.9.3.tar.gz
    ln -s redmine-0.9.3 redmine
    cd redmine
    cp config/database.yml.example config/database.yml
  8. Edit the ‘production’ section of ‘config/database.yml’ to configure it to use
    the database you created in step 1. ‘database’ and ‘username’ should be the
    name of the database, and ‘password’ should be the database password.
  9. Execute the following commands, again from your Redmine application directory. eg ‘cd ~/webapps/my_redmine_app/redmine
  10. RAILS_ENV=production rake config/initializers/session_store.rb
    RAILS_ENV=production rake db:migrate
    RAILS_ENV=production rake redmine:load_default_data
    cd ..
  11. Edit ‘nginx/conf/nginx.conf’ to change the text ‘hello_world’ to ‘redmine’.
  12. Restart nginx with the following command:
  13. ./bin/restart

You should now have a working Redmine install at the website you specified in step 3.

One last thing you will probably want to do is get a working email setup so that Redmine can email people. I used SMTP for this, the process is quite simple:

  1. Create a new mailbox to handle your Redmine email, making a note of the username and password.
  2. Go to your Redmine application directory, eg cd ~/webapps/my_redmine_app/redmine’ and execute the following:
  3. cp config/email.yml.example config/email.yml
  4. Edit ‘config/email.yml’ as described here, you will want to edit the ‘production’ entry as follows, replacing the place-holders accordingly:
  5. production:
      delivery_method: :async_smtp
      smtp_settings:
        address: smtp.webfaction.com
        port: 25
        domain: your_domain_name
        authentication: :login
        user_name: "your_mailbox_user"
        password: "your_mailbox_password"
  6. Restart nginx (see step 10 from above).

And that’s that. You should now have email working with your Redmine install.

[C++] Anything to/from a Hex String

Introduction

I recently needed to be able to convert any instance of an object in C++ to a file so it could be serialised, and then restored later; I did most of this by writing out each member variable of the object individually at the most basic level. This works fine and is easy enough to implement; but then came the time to do the “generic” version, the version that could write out any object (such as a struct) as a whole.

The I/O classes can write out/read in using either binary or text, the binary version of the generic writer is simply a case of writing out the length of the data, and then each byte of the data. The text version however required me to convert the bytes of data making up the object into something that was sensible as text, I decided to do this by converting each byte into a hex value and adding it to a string. As I was working on this I found that the information about how to do this without using some of the old C-style string manipulation functions is quite sparse on the net, so after much searching, trying, and failing, I now have a solution that works both ways using good old C++ string streams.

I should probably point out that I don’t think this solution is endian neutral, so you would likely want to add a method of endian detection and switching to ensure consistency across different architectures.

The Code

When a byte is encoded to hex string, each byte becomes two characters in the range 0 to F. For example, the value “10” would be written out as “0A”.

The code works by using a std::stringstream with hex mode set (std::hex), along with using zero’s for padding (std::setfill(‘0’)) and a fixed width of two for each byte added as hex (std::setw(2)).

The toHex function works by adding each byte of the passed data into the string stream as an integer with a width of two; because zero’s have been set as padding, any numbers which are added to the stream that are only one character long will be automatically prefixed with a zero resulting in the correct two character hex value being added to the string stream.

The fromHex function works by reading out two characters from the hex string into a string stream, these characters are then converted back into the byte value when read out from the string stream into an integer. Finally, the value of the integer is stored as the value of the byte, and the string is moved on to the next set of two characters.

Get the code.

[C++] Pointer Fun – SafeDelete

Introduction

SafeDelete and SafeArrayDelete are functions that will delete the data a pointer points to before setting it to NULL. The idea being that they leave the pointer in a safe NULL state so that you don’t try and use a pointer which points to invalid memory.

How to - With a Macro

You can implement a SafeDelete set-up using a macro, it might well look something like this:

#define SAFE_DELETE(ptr) { delete (ptr); (ptr) = NULL; }

Now that’s all well and good, and would perfectly do the job at hand, but we are C++ programmers and as such we prefer not to use macro’s unless we have to; after all, they can be tricky to debug since you can’t set breakpoints in them, they have no type safety which means you can come seriously unstuck if you pass something incorrect into one, and they can be tricky to read.

Attempt #1 – Just pass it a pointer… right?

Now, you might start off on your quest to convert that macro into a function by writing out the following code:

void safeDelete(void *ptr)
{
	delete ptr;
	ptr = NULL;
}

All looks fine, you are passing it in a pointer, deleting it and then setting the pointer to NULL… simple. So you use that in your application, the pointer is checked, it isn’t NULL so it gets deleted and set to NULL, cool. Then your code jumps out of the function and… what the hell?! The pointer passed into it is no longer NULL, but the data it points to has been deleted, the pointer is left dangling. Not a very safe SafeDelete.

So you’re now just left scratching your head, why did that happen? Simple, you passed a copy of the pointer into the function as a parameter, and you only changed that local copy.

People often have a misconception with pointers that they just somehow exist and magically point to a memory address, in actual fact, a pointer like the one shown above is an object on the stack that points to a memory address (also known as a pointee). If you know anything about that stack, that should tell you two things; firstly, the pointer object is passed into the function as a copy; secondly, that copy is destroyed once it falls out of scope.

The confusion over whether you are passing a pointer as a copy is easy to make since a pointer is essentially two things in one, this can be better explained by showing how const can work with a pointer.

void safeDelete(void *const ptr)
{
	delete ptr;
	ptr = NULL;
}

The above code should not compile, you should get an error about trying to assign to a value that is const. That is because you have made the pointer const, so you cannot change its value; this serves to clearly show that assigning NULL to the pointer is changing the pointer itself, and not the data it is pointing to.

Attempt #2 – A pointer to… a pointer?

If you want to be able to modify the location that a pointer points to after leaving a function (that is, essentially modify the pointer object itself) you need to pass it into the function like you would any other object that you want to modify; by using a pointer or a reference. First let’s look at the pointer to a pointer approach.

void safeDelete(void **ptr)
{
	delete *ptr;
	*ptr = NULL;
}

Well, that does the job all right. Note that you have to de-reference the pointer to a pointer that was passed into it before performing the required operations on it; this is so you are dealing with the pointer object you passed in from your function, and not the local copy of the pointer to a pointer.

The problem with this approach is that since pointers to pointers can’t be implicitly casted to a void** you have to do the cast yourself when passing to the function, which just looks ugly (and would get annoying fast).

int *ptr = new int(10);
safeDelete((void**)&ptr);

Attempt #3 – A reference to a pointer (and some trickery)

Just like you can created pointers to pointers, you can also create a reference to a pointer. These have all the usual features of references in C++ such as never being NULL, the syntax for creating such a thing is shown below.

void safeDelete(void *&ptr)
{
	delete ptr;
	ptr = NULL;
}

However, this code has a major flaw since it won’t compile. Why? Because you cannot create a reference to void so we need some template trickery to get this working correctly. As well as being able to create template classes, you can also create template functions and we will use this to our advantage to be able to create a reference to a pointer to a generic type.

template <typename T>
void safeDelete(T *&ptr)
{
	delete ptr;
	ptr = NULL;
}

This uses the template argument as the type for the reference to a pointer, this template trickery also allows us to do away with the nasty void** casting when using the function.

The final code

And here are the finished functions for safeDelete and safeArrayDelete.

template <typename T>
void safeDelete(T *&ptr)
{
	delete ptr;
	ptr = NULL;
}

template <typename T>
void safeArrayDelete(T *&ptr)
{
	delete[] ptr;
	ptr = NULL;
}

Note

You might be wondering why I don’t do an if to check if the pointer is non-NULL before trying to delete it. Well the default delete operators in C++ automatically ignore the deletion of a NULL (zero) pointer, so you can in-fact delete 0 as many times as you want; adding the if check does nothing but add extra CPU cycles.