March 12, 2010
Make and makefiles - a commented example to help you learn
If you're making an executable C++ file you build it from a whole lot of .o files, each of which you have compiled from a .cpp file. And you also build in library files. If you change a .cpp file, then you have to recompile it into a .o ... but don't forget that you also have to recompile the .cpp if you have changed any of the header files it includes. And the final build from .o to executable can be a long statement.
You might well say "oh - for goodness sake - put all the compile and build instructions in a batch file / shell script and run that when you change anything" and that can be quite effective for a small application but as the application grows:
• You won't want to recompile everything every time and
• You won't want to duplicate large numbers of similar compile instructions into your script.
This is where a Makefile comes in to play. A Makefile contains a series of instructions of the form "If file xxx does not exist, or is older than file yyy [from which it is created] the run the following instruction to (re)create file xxx". And the make utility applies this whole setup of dependecnises to work out what needs to be done, and goes off and does it.
For the straightforward Multiple Inheritance in C++ Example that I wrote about earlier, I provided a simple Makefile [here]. It contains directives of the sort:
Expense.o: Expense.h Expense.cpp
g++ -c Expense.cpp
which says that if Expense.cpp or Expense.h have changed more recently that Expense.o, you need to (re)run the gcc line that follows.
There are, though, many short cuts you can use in a Makefile to make it more compact, easier to edit, and to reduce duplication in it. Unfortunately, they make it far harder for the uninitialted to read the file. And it seems that this is a technology which Geeks tend to keep - "Secret Squirrel" to themselves; comments in makefiles are about as rare as daffodils in September!
I have taken the Makefile for the C++ multiple inheritance demo, and I have added in many of the more advanced techniques to show what can be done - and I've added comments too. You can find the complete Makefile [here] ... and you might like to note:
• I can define Macros with assignments
HEADERS=Film.h HireFilm.h Expense.h iostream
which I can then use further down my Makefile with a $(....) notation
Filmtest.o: Filmtest.cpp $(HEADERS)
This is commonly done not only for batches of header and object files, but also for the name of the C compiler and flags to the compile and load - typically CC=, CFLAGS= and LFLAGS=.
• As a special case, I can ask Make to look in a path for dependencies using VPATH
VPATH=/usr/include/c++/4.1.0
and I can add other directories for files who's names match a pattern using vpath [lower case]:
vpath %.txt ../docs
will say that make should look into the sibling docs directory for .txt file (note the use of % as a wild card in makefiles, rather like in MySQL).
• I can take a list of file names of one particular type and turn it into a list of file names of a different type:
HIGHSOURCE=Filmtest.cpp HireFilm.cpp
HIGHOBJ=$(HIGHSOURCE:%.cpp=%.o)
Defines HIGHSOURCE as being some source files, and HIGHOBJ as being the associated object files. Just add to the source list and you automatically add the the object list!
• The SUFFIXES rule(s) allow you to create a set of generic rules telling make how to turn one set of files (by extension) into another. First define the suffixes:
.SUFFIXES: .html .txt
then the rules:
.txt.html:
@echo "<html><body>" > $@
@cat ../docs/$< >> $@
@echo "</body></html>" >> $@
@echo "Web Page $@ created"
So in that example, if you ask the system to make a .html it will top and tail a .txt file from the .docs directory with html headers and footers. In this example,also note:
* @ to start a command means "do not echo this instruction"
* $< is used to refer to the incoming file for the conversion
* $@ is used to refer to the outgoing or target file.
• The first target in the file will be the one to be made if you don't give make any parameters, and if that target isn't a file name, the target will always be run.
all: Filmtest
@echo "The whole caboodle is now up to date"
In this case, with no file called "all", the code will always be run and you'll get the message
• You can define your own rules that are going to be used for most conversions of particular cases - here's a rule that shows how most .o files are made from .cpp files:
%.o: %.cpp %.h
$(CC) -c $(CFLAGS) -o $@ $<
Although that's a fallback rule and so it will be overridden where you provide an explicit rule.
• Finally, it's common to provide a dummy target "clean" to delete all temporary and interim files so that you can force a rebuild from scratch:
clean:
@-rm *.o
@-rm Filmtest
@-rm *.html
@echo "Clean dup"
In this case, the extra "-" sign tells make to carry on even if there was an error!
Here is an example of that makefile being run:
[trainee@easterton 007]$ make
g++ -c -O2 -pg Filmtest.cpp
g++ -c -O2 -pg HireFilm.cpp
g++ -c -O2 -pg -o Film.o Film.cpp
g++ -c -O2 -pg -o Expense.o Expense.cpp
g++ -o Filmtest -pg Filmtest.o HireFilm.o Film.o Expense.o
The whole caboodle is now up to date
[trainee@easterton 007]$ make
The whole caboodle is now up to date
[trainee@easterton 007]$ make about.html
Web Page about.html created
[trainee@easterton 007]$ make about.html
make: `about.html' is up to date.
[trainee@easterton 007]$
(I have added the -pg option since I uploaded the sample make file to the web site, as I was demonstrating how to set up and use tools such as the gprof profiler and the indent code tidy utility, but those are probably subjects for another day.)
Posted by gje at 03:30 PM
| Comments (0)
More about Graham Ellis of Well House Consultants
Related topics: via article database
Multiple Inheritance in C++ - a complete example
C++ and some other OO languages support multiple inheritance ... Java and some others do not, and it's often argued that multiple inheritance is an unnecessary complication. That may be the case in some languages, but certainly in Perl 5 it is necessary to have it to make use of eome of the modules supplied with the distribution.
Yesterday, I gave a tailored C++ course for an application which includes some quite somplex class relationships, and as a result I have produced a new and complete working example of multiple inheritance in C++ - it's a real "tutor's example" in that it uses the complexity for the sake of it, but it does show you the mechanisms.
Here are the files to look through:
Filmtest.cpp - the main program
HireFilm.cpp - the class that the main program uses, which inherits from both Film and Expense
Film.cpp - one of the base classes
Expense.cpp - the other base class
HireFilm.h - the header file for the class that does the multiple inheritance. This is where the interesting stuff is!
Film.h - The header file for one of the base classes
Expense.h - The header file for the other base class
Makefile - the file of dependencies and instructions that let you build the whole thing.
The "interesting stuff" is in HireFilm.h, which includes:
class HireFilm : public Film, public Expense {
public:
HireFilm(int boxo) : Film(boxo),unit(6.7) {};
void setcost(float);
float getcost(int);
HireFilm * longer(HireFilm *);
private:
float unit;
};
You'll see that the class is simply defined as inheriting first from Film and second from Expense (and there's a need to add in more logic if Film and Expense include conflicing methods).
And I have chosen as part of this demo to also show you how we can control which constructor a subclass calls in its base class(es) and how any extra parameters are set:
HireFilm(int boxo) : Film(boxo),unit(6.7) {};
A new Hire Film is to call up a base film (passing in a parameter that was passed in to hire film) as opposed to the default constructore call which will be to the base class constructor without parameters. It then sets the unit variable in the object to 6.7. Finally (and implicity - it's not stated in this line of code) it will call the base constructor of the Expense class without any parameters. Calls to base class constructors are always made, whether explicity or implicitly, as the variables within the base object need memory allocating for them.
There probably are times that multiple inheritance is a good idea in C++, but there are more times that it's used but unnecessary. The example above shows you how ... in "just" 7 source files, all of which you can click on, compile up and link through using the instruction in the 8th file - the Makefile.
We offer no less that 3 C++ courses - for delegates who have never programmed before, for delegates who have programmed before (but not in C), and for delegates who are converting from C. See [here] for further details of them.
Posted by gje at 07:31 AM
| Comments (0)
Related topics: via article database
March 11, 2010
Dear Planners, please provide viable alternatives
I have a meeting at Melksham Police Station this evening (of the Community Area Partnership - not on police business!) - from 7 p.m. to 9 p.m.
Melksham Police Station is about a mile and a half from home - outside the town on the old Semington Road. How can I get there?
I could drive. I've been there before, driving, and they only have very limited public parking. I think I counted six spaces, which for general vistors may sometimes be enough. But where there's an external meeting going on with some fifteen to twenty attendees, is woefully inadequate. I've parked on the roads outside, sharing the kerbside with 40 ton articulated lorries that don't seem to have found anywhere better either when they arrive long distance in Melksham and have to wait for the morning to unload. So - I'm being discouraged from driving. What are my other options?
I could walk. As the crow flies, the distance is reasonable. But following direct roads, I have to start on a fast "A" road without a footpath. There isn't a footpath down the second A road either, but at least there's a public footpath across the fields. They will be marshy at the moment, and it'll be very dark on my way back. The next longer route takes me through the industrial estate and also across a footpath that's potentially 'interesting' at night; the 'safe' route is much longer - virtually into the town centre and back out rather thanaround in an arc.
I could cycle. I don't know what parking's like for cycles at the Police Station, and I don't have a cycle these days ... but I do know that the shortest safe and available route - for me who's not the most practiced cyclist - is going to be via the town centre. That's not as big an issue of extra distance as it would be fo walking.
I could take the bus. Not a direct service, but the 271 / 272 / 273 from our road end, change to the 234 in the town centre and that stops right outside the police station. Ah - a good solution, until you look at the timetable. To be on time at my meeting, I'll have to catch the 17:05 bus, wait 51 minutes in the Market square, and arrive outside the Police Station an hour early. There's an 18:09 bus that will allow me to walk into the meeting about 10 minutes after it has started. On my return, the meeting finishes at 21:00. Bus leaves 21:40, change in the Town Centre; a wait of nearly 2 hours and I'll be at my home stop at 23:50.
I'm all for getting people to walk, cycle, use public transport where they can, and to encourage them to do so by restricting the amount of parking and pricing at at reasonable levels (above "free" but below "profiteering"). But if you are going to take a stick to people and force them out of their cares, you need to provide an adequate carrot alternative. This has clearly not been done in the case of the police station, where using the bus will mean I spend nearly 7 hours attending a 2 hour meeting, and where walking and cycling for those of us lucky enough to be fit enough to do so is dangerous via the practically short routes.
The example above is just one of many I could come up with - and there are lots of us who would reduce our car travel if only we practically could. Of all places, the police station should be easy to access for all, including those who are not mobile in their own right / can't afford their own transport / are ill and cannot drive (or walk or cycle).
Posted by gje at 11:47 AM
| Comments (0)
Related topics: via article database
Melksham - Carnival, Party in the Park, and Spot the Oddity
Saturday, 17th July 2010. There's a lot happening in Melksham, and here (for the newcomer) is a list of the events which are separately organised but co-operatively co-ordinated.
Melksham Carnival. The Melksham Carnival Parade assembles at Cooper Tires in the afternoon, and leaves at 6 p.m. to follow a route around the town. There will be a marching band, floats of all sorts (spectacular and otherwise) and you'll see the Carnival Queen and her princesses too. The Carnival is organised by the Carnival Committee - their web site is [here].
Spot the Oddity. From 9th July to 1st August, dozens of shops in Melksham will have "oddities" in their window displays, and local people and visitors to the town will be encourgade to go around and see if they can spot them. It's great fun for the young, the old, and the 'tweens. The entry form is printed in the Carnival program, and a small prize is given by the Chamber of Commerce, who organise the competition, for all forms returned (even if you don't find every oddity). There are also winner's prizes in a number of catergories - awarded after the closing date / hand in your forms by 4th August.
Melksham Party in the Park. The Party in the Park, which takes place in the King George V Playing Fields from 2pm onwards, is this year bigger and better than ever - with stalls, sideshows, music and entertainment aimed at all the family! Entry will be £3 (?) per person, which includes access to all the entertainments on offer, and the best view in town of the fireworks at the end of the evening. The Party in the Park has its own organising commitee and web site - see [here] and is a great fun afternoon and evening.
Me? I'm helping on the periphery to organise "Spot the Oddity", and doing some behind the scenes stuff for "the Carnival". On the day, I'll probably be on a stall in the afternoon, watching the carnival parade and taking photos - or perhaps even somewhere in the parade. There's plenty of food and drink and children's entertainment going on - what a great day for everyone from in and out of Melksham to participate and get involved - or just watch - and have fun whichever they choose to do.
Posted by gje at 07:01 AM
| Comments (0)
Related topics: via article database
March 10, 2010
Pointers to Pointers to Pointers - what is the point?
From today's course - a new example showing pointers to pointers to pointers. But why?
C pointers are useful in many ways:
• they let you pass a single value into a function that holds a whole collection of data
• they let you call by 'name' so that functions can alter values (see here)
• they let you access additional dynamic memory (example of that - here)
• they let functions return an item that's of unknown size.
But why pointers to pointers? Because they let you hold and process collections withing collections easily. As well as the first example, we have another example that does this - pascal's triangle all in dynamic memory - here.
And in real life, it can represent a whole data heirarcy too.
• I have a number of food product objects
• Each is in a dish object
• A number of dish objects meal up a meal object
• and we build up a collection of meal objects into a daily diet.
And we could go on.
• A familiy's daily diet objects makes a shopping object
• and a store's customers each day make up a turnover
I think I may have six levels of pointers there.
This all gets very hard to write and to look after; structured coding can help, but far better to use objects, which is where C++ comes in. I'm teaching a C++ Course tomorrow ... so I expect you may find some more examples along these line on the next blog entries.
Posted by gje at 06:35 PM
| Comments (0)
Related topics: via article database
Efficient use of dynamic memory - C and realloc
C is basically a language in which you dimension your arrays at compile time - however, at run time you can call up malloc or calloc to grab a chunk of dynamic memory. This is very useful if you don't know how much space you'll need at compile time. We've several example in our memory management module on our C training courses.
But sometimes, you'll only gradually learn how much memory you need, even at run time. Take, for example, a simple example where you want to read a file into memory and then be able to go through it, many times, line by line. You won't know how many lines there are at the beginning ... so a single malloc or calloc won't do. But there are solutions.
First, you could use realloc to extend the size of the memory block you have each time you add a new line.
Second, you could set up all your lines as linked lists, where each one contains a line of data and the address in memory of where the next line may be found.
The First option may lead to "thrashing" as memory is allocated and reallocated while the file is being read, with a large number of movements of the data between heap areas. And the second option may also be slow when you come to find data that's well down the list.
There is a Third Way. You can use realloc, but extend the size of the memory blocks in much more substantial chunks, and that's something that we did on today's course. The full source code may be found here. The extra lines / critical lines are:
need = counter + 1;
if (have < need) {
info = realloc(info,(counter+16) * sizeof(char *));
have = counter+16;
}
Basically saying "if you haven't got enough space for another line, then grab space for 16 more ...
Posted by gje at 06:18 PM
| Comments (0)
Related topics: via article database
March 09, 2010
Is it worth it?
Occasionally, I ask myself "is it worth it?". I write a lot of technical articles and add them to our website, and at times it feel like they're going into something of a void. It's rather like talking in a padded cell where any echo at all is notable by its absence.
But then I ask myself "how often do I write and say 'thank you' to the author of a web page that's given me a vital tip". The answer, is "far less than I should" - partly because I've moved on and partly because I don't want to take up someone's valuable time by sending him / her yet another fan letter.
But just occasionally, a note does appear posted through the obscure "rank and review" link, or by email, that says to me "yes - it IS worth it"". From my mail box the other day:
Oh, thank you, thank you. I've been struggling with a left join for... like forever, and your clear example just cracked it!
and that makes such a difference to me personally - thank you, Andrew, for writing that.
Looking around, I see and hear other evidence too that the material here is read, and services we provide are used. When we ask course delegates how they found us, it's often online. In Family Fortunes terms, that's the second most popular answer after "I was recommended to you". That online presence is bolstered, and our knowledge and background confirmed, by us providing good solutions to pressing issues even before a course is booked.
The count of visitors to a page is NOT necessarily an indication that the page itself is good / useful, merely that it's highly ranked by the search engines, or that it's about something which is a popular subject. I will admit, that an element of the ranking comes from how many people link in to the page, and how many are tempted by the few words that a search engine trails as a "teaser". So I'm only carefully proud of having over 1000 visits a day to our page that explains the difference between a JOIN to a LEFT JOIN, with fifteen other pages (yesterday's stats) in our technical article sections having over 100 visits each.
I have another measure too of the background work I put in - this one on the First Great Western Coffee Shop Passenger Forum that we seeded and host. Looking at my stats this morning, members have been logged in and online there for a total of 23,606 hours. At least 10 users have been there for over 20 days each. And that's not something that they would do unless it brought them something.
Finally, people I meet in real life comment on things I have written and they're usually very positive. In reality they may sometimes disagree with my more strident comments, but even if that's the case it's a heartwarming reminder that I'm not writing in that padded cell - it just feels like it sometimes.
Posted by gje at 06:12 AM
| Comments (0)
Related topics: via article database
March 08, 2010
Web page to telephone calls / links using an iPhone
Would you like people who visit your web site from their iPhone you be able to just click on your number and call you? Well - they can; the iPhone Safari browser recognized phone numbers and turns them into telephone links. But you might want a bit more control as the web site author ...
• To add a link that phones you, where the link is NOT a phone number, you can use a link of the form:
<a href="tel:+44-1225-708225">
• To suppress a link from a phone number, I have found that putting a start and end span tag in the middle does the trick:
0800 0<span></span>43 8225
• To link to a different number that the one shown on your page, simply add your own link around the number:
<a href="tel:+44-1225-708225">01225 708225</a>
This is potentially open to abuse (eg. offer a freephone number but link to a similar number that costs), but my example is a sensible one as it lets me display my number as expected by my UK customers, but then converts it so that the link will work internationally (worldwide) if someone follows it from overseas.
The tel: protocol isn't supported by all browsers, though, and if you want to avoid offering links that do strange things when selected on your computer (as opposed to your phone), you'll need to recognise the browser and only provide the links where it's appropriate.
Here's a simple example of how you might to this (in PHP):
• Recongise if the phone is an iPhone:
<?php $iphone = preg_match("/iPhone/",$_SERVER[HTTP_USER_AGENT]); ?>
• And if it is an iPhone, send an extra link:
<?php if ($iphone) print ('<a href="tel:+44-1225-708225">'); ?>
then add in the link content such as an image, then:
<?php if ($iphone) print ("</a>"); ?>
| Do you have Flash in your web page? And do you want your application to work well on the iPhone? The default iPhone browser does not support Flash ... there are various ways to get an iPhone to render Flash ... but rather than put your potential customer to the trouble, why not use the PHP above and send out an alternative? |
I like to provide a "try it here" page with all my Blogs, but it this case I don't think I will - Lisa would be really happy with me if she got a lot of "just testing" phone calls ... however, on the Well House Consultants home page and on the Well House Manor Home page, clicking on the big text than announces our name will offer you a call to us. Please use it if you would like to book a weekend away, or a course ;-)
| If you're not familiar with PHP, have a look at our courses - we offer a variety of curricula, depending on your background and on what you want to be able to do with the language. |
Posted by gje at 12:59 PM
| Comments (0)
Related topics: via article database
Random thoughts on Melksham Town Planning and development
On Friday evening, I attended the Mayor's reception in Melksham Assembly Hall, and on Saturday I traveled to Taunton to attend TravelWatch SouthWest. At one of those meetings (and I'm ashamed to say I can't recall which) someone made the poignant comment that, for the most part, Town Planners don't actually "town plan" much any more - that the town planning and layout of the newly developed and redeveloped areas is very much in the hands of the big building companies, who want to get as high a return as possible from the land they have invested in ... with the town planners acting much more as a 'control' to avoid them going too far off plan. This somewhat cynical view sounds pretty depressing, but there's an element of truth in it. One hopes that the customer for a new house would baulk at purchasing something that has no access or local amenities, but in reality I suspect that a shiny new house will tempt many people to overlook potential access and service issues they'll discover - or grow used to - later.
In yesterday's "Horse's Mouth", I showed pictures of Melksham's river frontage and countryside, taken on a long dog walk to give her exercise (she runs 5 miles for each mile I walk!) and to clear my lungs. I took further pictures too which are less "pretty" and more thought provoking:
Heavy Industry sits right across from housing (and there's a distinct rubbery smell from the factory). A Road and housing that was in place long before a family car was the norm is now getting quite hard to negotiate. And - if this picture were used in a Geography / town planning exam, I'm sure comment would also be made on the satellite dish. Very Interestingly, this location is close to a supermarket and bus and rail connections and - in times to come - will suit the much greener agenda. But then as people, perhaps, drop from two cars per family to one, there won't be quite such a need for the tyres manufactured on the right. This is an emotive subject, as the plant employs the best part of a thousand people.
Housing development on the fields to the east of the town - away from the main trunk A350 road and the railway line. The Snowberry Lane development - from which this forms a further offshoot - is a glorified cul-de-sac and you can get in and out on foot, by cycle, or by car. Walking in "to town" is feasible for the more energetic of us. Cycling has its "pinch points" where there's an uncomfortable sharing of pavement and / or roadway with other traffic, to the restriction of easy movement for all concerned, and gives reduced safety to young cyclists. And there's no bus service there.
The importance of a local bus service was highlighted on Friday evening at the Mayor's reception, with a community award to the regular driver of the "No. 14" which provides a link from various parts of Melksham into the town - it's clearly a valued and much needed service. But it doesn't serve Snowberry Lane - there's not time in its schedule for a "double back" route which in any case would irritate the regulars with an elongated journey. And yet a bus gate from Dorset Crescent to Heather Avenue would fix that ...
Perhaps it's unfair to look at transitional conditions during a build - but for the record, here is one of our favorite walks as it is at 9th March 2010 - only just passable through the mud, but with very large numbers of footprints to confirm that it is heavily used.

Given time, areas that were in the country get very much build into the town - contrast the fields at Snarleton Lane yesterday with "The Ridgeway" - a path that runs between the houses from Church Lane to the Sandridge Road in Melksham Forest and which (an educated guess) is an old pathway from long before The Forest was built. Now that the developers of Melksham Forest are long gone, the path is very passable / usable, although it's not quite the relaxing and refreshing walk that it once would have been. But we should remember that even on the most pessimistic development plans (i.e. the largest amounts of sprawl), we're only looking at 2% of the rural land being taken by development in the next 50 years, and if that 2% were to become 2.5%, but then 20% of the area taken was given over to greens and cycle ways and a pleasant environment, I don't think I would be too unhappy.
Posted by gje at 08:52 AM
| Comments (0)
Related topics: via article database
March 07, 2010
Early Spring walk in Melksham
The subject lines says it all, really! In the afternoon, full of a cold and not concentrating on other things, I was tempted into a long walk by an energetic and willing companion who - if you look very carefully - you'll find in one of these pictures.





From top to bottom - the field behind Snarleton Lane, the Millenium walk alongside the river Avon - the northern section (two photos), then the southern section, and finally in Conigre Mead nature reserve.
The interesting thing is that many of these scenes are set to change ... with housing already spreading onto the fields in the sector between Snarleton Lane and The Spa, and with the canal coming along into the river. All of which are signs of a town that's growing in confidence and stature and size, and has a great heart.
There have been many discussions as to which direction the town *should* be going in and I'm not going to get involved in those here. I will point out that the well used public footpath across the field shows just how many people make use of the countryside for walks, and that paths that are lost into the urban sprawl need to be replaced by other popular paths; that's not so much a question of designating new public footpaths, but rather of adopting and making popular the "next series out", some of which are currently very hard to follow.
Posted by gje at 11:48 PM
| Comments (0)
Related topics: via article database
March 06, 2010
Oliver Cromwell at Bristol Temple Meads

I've been to Taunton today - a meeting of TravelWatch SouthWest which I'll be documenting elsewhere. But I couldn't resist this picture of Oliver Cromwell - Britannia class 4-6-2 locomotive no. 70013 - which was in Bristol Temple Meads on our return and set off from there on a special trip, named "The Bristolian", while we waited for our return train to Chippenham.
Posted by gje at 06:59 PM
| Comments (0)
Related topics: via article database
