Skip to content

Lazarus: Risen From The Grave?

Introduction

Like many programmers "of a certain age" (such as the divine Ms. Stob), I used to do a lot of work with Borland’s Delphi product. When this came out back in 1995, it trounced its main rival, Visual Basic, both in terms of ease-of-use and of performance. Unfortunately, criminal incompetence on the part of its various owners, and the departure of its chief architect to Microsoft (where he designed C#, among other products) has seen its market share dwindle to almost nothing in recent years, and its pricing structure hasn’t helped, in an era of free software.

However, Delphi has always had its fanatical adherents, and some of them have created an Open Source version of the product called Lazarus. Available for Windows, Linux and the Mac, Lazarus provides a complete IDE for developing GUI applications (and non-GUI ones, if the fancy takes you) using the Object Pascal programming language. In this article, I kick the tyres of Lazarus by writing a very small "hello world" application.

Hello World

I am renowned for my exquisite taste in GUI design, and here is the final result of my labours using Lazarus. The user enters their name, clicks on a button, and the app greets them. After 5 seconds, both the input and the greeting fields are cleared automatically.

laz-done

I’ll now show you how I created this magnificent application!

Launching Lazarus

When you start Lazarus (which is a very fast operation compared with the likes of Visual Studio), you will be presented with a default application project containing a single empty form:

laz-start

The GUI should be familiar to old Delphi users, and won’t hold many surprises for others. At the top, you have the menu and toolbar, together with a tabbed palette containing the numerous GUI and non-GU controls that Lazarus provides. To the left is the object inspector, which allows the properties of the controls to be changed. In the centre are the two windows for editing the code and the components of the form you are working on, and at the bottom is a window for compiler messages and the like. Lazarus is resolutely multi-window – there is no option to tile the IDE.

Changing Properties

The first thing I want to do is to change some of the properties of the form. I’m going to change its title, and give it a non-sizable border. To do that, I clicked on the form in the IDE and then started changing things in the Object Inspector. First the form’s title; notice that as the form is also a control it uses the name "Caption" for this property:

laz-title

Changing the border style uses a dropdown menu provided by the Object Inspector:

laz-border

I want a non-sizeable, dialog-style border, so I chose bsDialog.

Testing The Changes

One of the main advantages of an IDE is that it encourages the "make a small change and see if it worked" style of programming, which discourages bugs from creeping into the code. I now want to run the program to see if the changes I’ve made look good. To do that, I simply hit the Run button on the toolbar. It’s here that difference from Delphi becomes obvious – the compile and link times for the program are nowhere near as good as they would be for Delphi. It’s not exactly slow (certainly its faster than a C++ compile and link would be), but there is a definite pause. Anyway, the resulting form looks fine:

laz-form1

Adding Controls

Time now to add some controls to the form. You do this by dragging them from the palette below the IDE’s menu:

laz-palette

As well as the "standard" controls, such as buttons and text edits, Lazarus comes with a wide variety of other controls (about 200 in all) to provide facilities like data aware grids, standard dialogs etc. And it’s easy to create your own controls from scratch, or to modify existing ones using inheritance. I added a couple of labels, a text edit and a button to the form, and used the Object Inspector to give them more meaningful names than the defaults provided by Lazarus, and to change their captions where appropriate:

laz-controls

Lazarus provides numerous options for aligning controls, which I used to make the "Who are you?" prompt and the associated text edit line up vertically.

Adding An Event

Like all modern GUI builders, Lazarus is event driven. Nothing much happens until the user clicks on a control, or performs some other action, at which point one or more event will fire. Events are associated with particular controls, I want to add an "OnClick" event to the "Greet" button which will read the text the user entered and set the "Greeting" label accordingly. Events are added from the Object Inspector:

laz-onclick 

I double-clicked on OnClick, and Lazarus generated the following event handler for me:

laz-event1

The event handler, like all Lazarus code, is written in Object Pascal. This will never be my favourite language, but it’s pretty easy to understand, and easy to pick up if you have a background in languages such as C++, Java or C#. The code I added to the handler looks like this:

laz-event2

The editor has code completion, but only for looking up method names – it won’t complete half-completed names like "Greet" in this case.

With this even handler in place, I can click on the button and have the app say "Hello" to me. I now want to reset the user input and the greeting to be empty after 5 seconds have elapsed. To do this, I need to add a timer to the form.

Adding a Timer

Timers are  controls which you add to the form in the same way as buttone stc. but which have no visual representation at run-time. The timer control can be found in the "System" palette:

laz-syspal

I placed a timer on the form, and then changed its Enabled property to False, and its interval to 5000 milliseconds. Then I modified the button event handler:

lazevent3

So when the button is clicked, the timer is enabled and the countdown commences. I now need to provide an event handler on the timer to clear the label and text edit:

laz-event4

And with that, the application is pretty much complete. I made a couple of cosmetic changes, such as the greeting’s font, but that’s about it.

Other IDE Features

Lazarus is a reasonably full featured IDE; as well as the code and form editing, you get some refactoring support and an integrated debugger. I was quite interested to see how the debugger performed, as I’ve always found the one in Delphi itself rather poor. So I set a breakpoint in the timer event handler and ran the app again. It quickly becomes clear that the debugger is none other than gdb, which could be a good thing or a bad thing, depending on your feelings about gdb. Lazarus does quite a nice job of putting a windowed interface on top of it, but I suspect that gdb’s problems when been driven from a GUI will show through if I ever needed to do anything complex in the way of debugging.

Conclusion

Lazarus  makes a very good stab at being a free, open-source Delphi clone. There are some rough edges, and the compile/link times could be a bit better, but on the whole I was pretty impressed with it. People looking for a GUI builder that works cross-platform on Windows, Linux and the Mac should consider giving it a try.

Investigating C++11 Threads

Introduction

I’ve been writing multi-threaded code, mostly for servers, for many years now, but I’ve always used native threads on Windows and Solaris, the portable pthreads library, or various commercial threading libraries, such as RogueWave. I’ve always had a somewhat sneering attitude to the C++ Standard Library threads, as I assumed they wouldn’t provide all the features I need, and would never be fully implemented. But recently I realised that this was a somewhat blinkered way of looking at things, and that maybe it was time to investigate the C++ library threads a bit more deeply.

What follows is how I wrote a very simple application to check out the C++ threads library features. It won’t contain any startling information  for people who already know the library, but may be of interest to those who don’t. You don’t need any great C++ expertise to follow it, but if you want to build the code you will need a fairly up-to-date C++ compiler. I used the excellent Windows MinGW-builds 64-bit compiler, GCC version 4.7.2, which has become my compiler of choice recently.

A Simple Program

The program I chose to write was that beloved of all people writing threading examples. It simply prints out some numbers sequentially. Here’s the single-threaded version:

#include <iostream>
using namespace std;

void printnums( int start, int n ) {
    for( int i = 0; i < n; i++ ) {
        cout << "[" << start + i << "]" << endl;
    }
}

int main() {
    printnums( 0, 100 );
}

which produces the exciting output:

[0]
[1]
[2]
...
[99]

and is executed by the thread automatically created for you by the C++ runtime when you execute main(). So, how to run the printnum() code in a separate thread? Time to dive into the documentation. Although it is far from perfect, I recommend www.cppreference.com for this purpose.

Creating A Thread

Using the above reference, it seems that all I needed to do was to create  a std::thread  object, passing the thread’s constructor the name of the function I wanted to run, and its parameters:

#include <iostream>
#include <thread>
using namespace std;

void printnums( int start, int n ) {
    for( int i = 0; i < n; i++ ) {
        cout << "[" << start + i << "]" << endl;
    }
}

int main() {
    thread t1( printnums, 0, 100 );
}

This is a lot simpler than the native thread libraries, which are basically C APIs and require you to mess with void pointers and custom structs to pass the parameters to the function you want implemented. A big plus for the C++ library implementation!  Note that I could have also bound the parameters to the printnums() function myself, like this:

thread t1( bind( printnums, 0, 100 ) ); 

which is what the thread constructor is doing for me – for more info on std::bind, see this other blog article of mine.

I compiled this code with the MinGW-builds compiler like this:

g++ -std=c++11 -Wall -Wextra athread.cpp

The -std=c++11 option tells the compiler I’m using features from the C++11 Standard, and the other two options are my standard warning levels. Somewhat to my surprise, it  built with no errors, particularly no linker errors. I was surprised because my past experience with building any C++ code that uses pthreads (which this implementation of C++11 is using under the hood) normally requires all sorts of messing with explicitly telling the build system that you are using pthreads. Not so here – a big plus for the MinGW-builds implementation!

However, running the program was not such a happy experience. It did indeed print out all the numbers I expected, but then terminated with everyone’s favourite Windows dialog:

stoppedworking

Why would this be? Well, as a somewhat experienced threads programmer I actually knew the answer to this one. My program really had two threads – the one started for me automatically in main(), and the one I started explicitly via the std::thread constructor. The parent thread is the one in main, and if that thread exits before any child threads  it has created exit, then all bets are off, and you are in Undefined Behaviour Land. In this case, the program crashed – you might be less lucky, and have such a program appear to "work".

The fix for this is usually pretty simple – whatever threading library you are using will provide some function to allow the parent thread to wait for the child thread(s) to exit. Thread library writers love giving this function bad names – typically "join", because it "joins the two threads back together". Actually, it does no such thing, but that’s library writers for you.

So the fix for my program (after a quick check to see that the C++ library does use that bad name "join") was to re-write main() like this:

int main() {
    thread t1( printnums, 0, 100 );
    t1.join();
}

This made the main() thread wait until the t1 thread exits, and so all is well and I got a  nice list of numbers.

Two Explicitly Created Threads

I now had two threads running (one implicitly created, the other explicitly), so the next thing to try was creating creating another thread, which prints numbers starting at 1000 instead of zero:

int main() {
   thread t1( printnums, 0, 100 );
   thread t2( printnums, 1000, 100 );
   t1.join();
   t2.join();
}

This produced two streams of numbers in parallel  – one beginning at 0, and one at 1000. The streams were interleaved, but the output looked somewhat screwed up. On my system, it looked like this;

[[1000]0]
[1]
[2]
[3]
[4
[1001]

The reason for this is that I hadn’t serialised the access to the single std::cout object. The C++ Standard says that multiple threads may safely access C++ ostreams, but makes no guarantee that the output produced will be sensible. I needed to use a mutex to make sure that only one thread at a time was writing to cout – back to the documentation!

Mutexes

The Standard Library provides a variety of mutexes, declared in the header file <mutex>. A very simple one would do for my purposes, so I rewrote my code like this:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

void outnum( int n ) {
    static mutex m;
    m.lock();
    cout << "[" << n << "]" << endl;
    m.unlock();
}

void printnums( int start, int n ) {
    for( int i = 0; i < n; i++ ) {
        outnum( start + i );
    }
}

int main() {
    thread t1( printnums, 0, 100 );
    thread t2( printnums, 1000, 100 );
    t1.join();
    t2.join();
}

The mutex needs to be static so that all threads that enter the outnum() function use the same mutex.

This code worked well; the output from the threads is no longer jumbled together. However, I was a bit worried by having to unlock the mutex manually. Whenever you find yourself doing this kind of thing, it’s best to create a helper class that will do the unlocking using RAII. That way, if the locked code ever throws an exception, the mutex will be automatically unlocked.

It turns out I didn’t need to write such a class myself – one is provided by the Standard Library. I simply needed to modify my code like this:

void outnum( int n ) {
    static mutex m;
    lock_guard <mutex> g( m );
    cout << "[" << n << "]" << endl;
}

This creates a lock_guard object who’s constructor calls lock() on the mutex. When the guard object goes out of scope (or an exception is thrown), the guard’s destructor will call unlock() to release the mutex.

Sleeping

Everything was working nicely, but the output of the program was fairly zooming off the screen. It’s quite common in multi-threaded code to want to "throttle" the threads in some way. One common means of doing so is to put a thread to sleep for a period. The C++ thread library provides a couple of sleep functions, defined (largely for readability purposes, as far as I can see) in the this_thread namespace. Traditionally, multiple sleep functions (sleep and usleep, for example) have been provided by libraries depending on how long you wanted a thread to sleep, but the C++ threads library makes use of another library feature, the chrono namespace, to define the sleep period in a flexible manner:

void printnums( int start, int n ) {
    for( int i = 0; i < n; i++ ) {
        outnum( start + i );
        this_thread::sleep_for( chrono::milliseconds( 200 ) );
    }
}

This puts the thread to sleep for 0.2 seconds, and results in nicely readable output speed.

Conclusion

This article has looked briefly at the major features (but by no means at all the features) of the C++ Standard Library threads. I was pleasantly surprised at how easy the library was to use, particularly compared with C thread implementations like Windows threads  and pthreads. The use of C++ features makes the much easier to read and to write, and I will definitely be using C++ threads in future projects in preference to native threads, implementations permitting, of course.

Common C++ Error Messages #1 – No such file or directory

Introduction

In this intermittent series, I’ll be looking at the most common error messages your C++ compiler (and linker) can produce, explaining exactly what they mean, and showing how they can be fixed (or, better still avoided). The article will specifically talk about the errors produced by the GCC command line compiler, but I’ll occasionally provide some coverage of Microsoft C++ as well. The articles are aimed at beginner to intermediate C++ programmers, and will mostly not be OS-specific.

Error Messages 101

Compiler error messages from the GCC g++ compiler generally look like something this:

main.cpp: In function 'int main()':
main.cpp:4:12: error: 'bar' was not declared in this scope

which was produced by this code:

int main() {
    int foo = bar;
}

The first line of the error says which function the following error(s) is in. The error message itself comes in four main parts; the file the error occurs in, the line number and character offset at which the compiler thinks the error occurs, the fact that it is an error, and not a warning, and the text of the message.

As well as error, the compiler can also produce warnings. These are usually about constructs that, while not being actually illegal in C++, are considered dubious, or constructs that the compiler has extensions to cover. In almost all cases, you don’t want to use such constructs, and you should treat warnings as errors; in other words, your code should always compile with zero warnings. You should also increase the level of warnings from the compiler’s default, which is usually too low. With g++, you should use at least the -Wall and -Wextra compiler options to do this:

g++ -Wall -Wextra myfile.cpp

 

No such file or directory

The error I’m looking at today most commonly occurs when you are including a header file using the preprocessor #include directive. For example, suppose you have the following code in a file called myfile.cpp:

#include "myheader.h"

and you get the following error message:

myfile.cpp:1:22: fatal error: myheader.h: No such file or directory
compilation terminated.

What could be causing it? Well, the basic cause is that the compiler cannot find a file called myheader.h in the directories it searches when processing the #include directive. This could be so for a number of reasons.

The simplest reason is that you want the compiler to look for myheader.h in the same directory as the myfile.cpp source file, but it can’t find it. this may be because you simply haven’t created the header file yet, but the more common reason is that you either misspelled the header file name in the #include directive, or that you made a mistake in naming  the header file when you created it with your editor. Look very closely at the names in both the C++ source and in your source code directory listing. You may be tempted to think "I know that file is there!", but if the compiler says it isn’t there, then it isn’t, no matter how sure you are that it is.

This problem is somewhat greater on Unix-like system, such as Linux, as there file names are character case sensitive, so Myheader.h, MyHeader.h, myheader.h and so on would all  name different files, and if you get the case wrong, the compiler will not look for something "similar". For this reason, a very good rule of thumb is:

Never use mixed case when naming C++ source and header files. Use only alphanumeric characters and the underscore when naming C+++ files. Never include spaces or other special characters in file names.

Apart from avoiding file not found errors, this will also make life much easier if you are porting your code to other operating systems which may or may not respect character case.

The wrong directory?

Another situation where you may get this error message is if you have split your header files up from your C++ source files into separate directories. This is generally good practice, but can cause problems. Suppose your C++ project is rooted at C:/myprojects/aproject, and that in the aproject directory you have two sub-directorys called src (for the .cpp files) and inc (for the header files), and you put myfile.cpp  in the src directory, and myheader.h in the inc directory, so that you have this setup:

myprojects
  aproject
    inc
      myheader.h
    src
      myfile.cpp

Now if you compile the source myfile.cpp from the src directory, you will get the "No such file or directory" error message. The C++ compiler knows nothing about the directory structures of your project, and won’t look in the inc directory for the header. You need to tell it to look there somehow.

One thing some people try when faced with this problem is to re-write myfile.cpp so it looks like this:

#include "c:/myprojects/aproject/inc/myheader.h"

or the slightly more sophisticated:

#include "../inc/myheader.h"

Both of these are a bad idea, as they tie your C++ code to the project’s directory structure and/or location, both of which you will probably want to change at some point in the future. If the directory structure does change, you will have to edit all your #include directories.The better way to deal with this problem is to tell the compiler directly where to look for header files. You can do that with the compiler’s -I option, which tells the compiler to look in the specified directory, as well as the ones it normally searches:

g++ -Ic:/myprojects/aproject/inc myfile.cpp

Now the original #include directive:

#include "myheader.h"

will work, and if your directory structure changes you need only modify the compiler command line. Of course, writing such command lines is error prone, and you should put such stuff in a makefile, the use of which is unfortunately outside the scope of this article.

Problems with libraries

Somewhat similar issues to those described above can occur when you want to use a third-party library.  Suppose you want to use the excellent random number generating facilities of the Boost library. If you are copying example code, you may well end up with something like this in your C++ source file:

#include "boost/random.hpp"

This will in all probability lead to yet another "No such file or directory" message, as once again the compiler does not know where "boost/random.hpp" is supposed to be. In fact, it is one of the subdirectories of the Boost installation, and on my system I can get the #include directive to work using this command line:

g++ -Ic:/prog/boost1461 myfile.cpp

where /prog/boost1461 is the root directory for my specific Boost library installation.

Can’t find C++ Standard Library files?

One last problem that beginners run into is the inability of the compiler to find header files that are part of the C++ Standard Library. One particular favourite is this one:

#include <iostream.h>

where you are learning C++ from a very, very old book. Modern C++ implementations have not contained a file called iostream.h for a very long time indeed, and your compiler is never going to find it. You need to use the correct, standard names for such headers (and to get a better book!):

#include <iostream>

If this still fails, then there is almost certainly something very wrong with your GCC installation. The GCC compiler looks for Standard Library files in a subdirectory of its installation, and locates that directory relative to the directory containing the compiler executable, so if the Standard Library headers are available, the compiler should always find them.

Conclusion

This article looked at the "No such file or directory"  message of the GCC C++ compiler.  If you get this message you should:

  • Remember that the compiler is always right in situations like this.
  • Look very closely at the file name to make sure it is correct.
  • Avoid naming file using mixed-case or special characters.
  • Use the -I compiler option to tell the compiler where to look for files.
  • Make sure that GCC is correctly installed on your system.

Learning Go – Miniblog #14 – Closures and Goroutines

This carries on from here, and started here.

OK, I have two remaining problems. The first is that I want my index request handler to be able to provide a custom title for the index page (and have similar functionality for the data directory in the data handler). The index handler currently looks like this:

func csvIndexHandler( rw http.ResponseWriter, req *http.Request ) {
    fmt.Fprintf( rw, "<h1>CSV index</h1>\n" )
    listIndex( rw )
}

but somehow I want it to have access to the title that was provided when the server was created.

I thought of all sorts of hacky solutions to this problem (global variables and whatnot), but then I remembered reading in A Tour of Go that the language supported functions as first-class object, and indeed it does. I’d forgotten that it also supports closures, which is exactly what I was looking for. I junked the standalone index handler and re-wrote it as a function value in the NewServer constructor function:

func NewServer( port, title, datadir string ) (*Server) { 
    s := &Server{port, title,datadir,&http.Server{Addr: ":"+port, Handler: nil } }
    mux := http.NewServeMux()
    mux.HandleFunc( CSVROOT + IDXSTR + "/", 
        func ( rw http.ResponseWriter, req *http.Request ) {
            fmt.Fprintf( rw, "<h1>%s</h1>\n", title )
            listIndex( rw )
        })
    // similar for data handler here
    s.https.Handler = mux
    return s
}

This is a bit horrible to read (later, I created the function value in a separate helper function), but you can see that I’m creating a nameless  function value which then gets passed to HandleFunc to add it as a handler to the multiplexer. A function object defined like is a closure over the variables in the enclosing function, and so gets access to the "title" variable, which it then uses to create the HTML for the index page. Similar code (not shown) creates a function value to handle data requests, and gets access to the "datadir" variable. This all worked like a charm

My last problem was to prevent the call to the Serve() function from blocking so that I could run more than one server at once. This turned out to be trivially easy – I just ran the first server as a "goroutine", which is Go parlance for a lightweight thread. Starting the thread is as simple as saying "go":

func main() {
    s1 := csvsrv.NewServer( "8080", "My Little Server", "csvdata" )
    go s1.Serve() // note go to run new thread
    s2 := csvsrv.NewServer( "8085", "Another Server", "csvdata" )
    s2.Serve()
}

So that’s it, a multi-threaded HTTP server that serves CSV data files as HTML tables, which is what I set out to achieve here. In the final article in this series, I’ll post some thoughts on how easy it was to do, and on learning Go in general.

Addendum: I’ve decided not to write the final article yet, as in the past I’ve always maintained that you need to have done a real-life project (at least 6 man-months) using a language before you can critique it, so criticising Go after only a tiny toy project like this would be hypocritical. Though I would say that the Go guys need to work a lot harder on the documentation – particularly, it needs a lot more examples!

Learning Go – Miniblog #13 – More On Server Objects

This carries on from here, and started here.

My original server code used the "default" HTTP server instance provided by Go’s library. Unfortunately, this (as far as I can tell) only allows you to listen on a siungle specific port, and only supports one set of request handlers. I want  to create multiple servers, capable of listening on multiple ports, and (possibly) having different sets of request handlers.

The Go library does support an http.Server type, so I modified my struct definition to contain a pointer to one:

type Server struct {
    port, title, datadir string
    https *http.Server
}

I then modified my NewServer function to create an http.Server (note despite similar names, csvsrv.Server and http.Server are distinct types):

s := &Server{port, title,datadir,&http.Server{Addr: ":"+port, Handler: nil } 

This allows me to create an http.Server instance listening on a specified port. It doesn’t solve the request handling problem however. To do that I had to dig through the documentation (aargh!) to find that the handling is performed by a type called ServeMux. As with the server type, the Go library provides a default, but I wanted a custom one. The http.Server class has a member called Handler (set to nil in the code above) to support a custom ServeMux, so I created one and added my existing handlers to it. The resulting implementation of my NewServer method looks like this:

func NewServer( port, title, datadir string ) (*Server) { 
    s := &Server{port, title,datadir,&http.Server{Addr: ":"+port, Handler: nil } }
    mux := http.NewServeMux()
    mux.HandleFunc( CSVROOT + IDXSTR + "/", csvIndexHandler )
    mux.HandleFunc( CSVROOT + DATASTR + "/", csvDataHandler )
    s.https.Handler = mux
    return s
}

I also needed to add a member function to make the server actually do something:

func (s *Server) Serve() {
    s.https.ListenAndServe()
}

With those in place, I actually had a working custom server! This code creates a server and starts it serving:

s1 := csvsrv.NewServer( "8080", "My Little Server", "csvdata" )
fmt.Printf( "Port: %s Title: %s Data: %s\n", s1.Port(), s1.Title(), s1.Datadir() )
s1.Serve()

Now only two problems remain to deal with – I need somehow  to "inject" the index title and data directory values into the request handler functions, and I need to deal with the fact that my Serve() function is blocking, so I cannot run another server instance.