Complete roguelike tutorial using C++ and libtcod - extra 2: debugging

From RogueBasin
Jump to navigation Jump to search
Complete roguelike tutorial using C++ and libtcod
-originally written by Jice
Text in this tutorial was released under the Creative Commons Attribution-ShareAlike 3.0 Unported and the GNU Free Documentation License (unversioned, with no invariant sections, front-cover texts, or back-cover texts) on 2015-09-21.


Sooner or later (and always sooner than expected), you will do something wrong in your code and the result will be a sudden, brutal, impolite crash of your application.

This article will show you how to debug the application with a command line debugger. I know it's easier to use an IDE and I might add a dedicated article on debugging with CodeLite. But you don't always have an IDE available. Your favorite IDE might not be ported to some obscure platform you want your game to run on. gdb is always a useful addition in any C/C++ developer's swiss army knife.

Let's crash

For example, let's do some minor change to the Engine constructor and move the map creation before the player creation :

map = new Map(80,45);
player = new Actor(40,25,'@',TCODColor::white);
actors.push(player);

This seems totally inoffensive. Let's recompile the game as usual :

Windows :

> g++ src/*.cpp -o tuto -Iinclude -Llib -ltcod-mingw
-static-libgcc -static-libstdc++

Linux :

> g++ src/*.cpp -o tuto -Iinclude -L. -ltcod -ltcodxx -Wl,-rpath=.

Now if you run the game, you should see the game window disappearing as soon as it opens. No error message, no nice stack trace. What the hell ? Well welcome to native application coding.

Adding debugging information

To be able to understand what's happening, we need a debugger. And for the debugger to be able to track what the program is doing, we need to add information in the .exe. With g++ you do that with the -g flag.

We'll also go further and use the libtcod library that also contains debugging information. That means adding -debug to the library names in the compilation command :

Let's recompile with debugging information :

Windows :

> g++ src/*.cpp -o tuto -Iinclude -Llib -ltcod-mingw-debug
-static-libgcc -static-libstdc++ -g

Linux :

> g++ src/*.cpp -o tuto -Iinclude -L. -ltcod_debug
-ltcodxx_debug -Wl,-rpath=. -g

Ok, now our game is bigger, probably slightly slower, but we can see what it's doing while running.