An Introduction to C & GUI Programming – the new book from Raspberry Pi Press

The latest book from Raspberry Pi Press, An Introduction to C & GUI Programming, is now available. Author Simon Long explains how it came to be written…

An Introduction to C and GUI programming by Simon Long

Learning C

I remember my first day in a ‘proper’ job very well. I’d just left university, and was delighted to have been taken on by a world-renowned consultancy firm as a software engineer. I was told that most of my work would be in C, which I had never used, so the first order of business was to learn it.

My manager handed me a copy of Kernighan & Ritchie’s The C Programming Language, pointed to a terminal in the corner, said ‘That’s got a compiler. Off you go!’, and left me to it. So, I started reading the book, which is affectionately known to most software engineers as ‘K&R‘.

I didn’t get very far. K&R is basically the specification of the C language. Dennis Ritchie, the eponymous ‘R’, invented C, and while the book he helped write is an excellent reference guide, it is not a great introduction for a beginner. Like most people who know their subject inside out, the authors tend to assume that you know more than you do, so reading the book when you don’t know anything about the language at all is a little frustrating. I do know people who have learned C from K&R, and they have my undying respect!

I ended up learning C on the job as I went along; I looked at other people’s code, hacked stuff together, worked out why things didn’t work, asked for help from my colleagues, made a lot of mistakes, and gradually got the hang of it. I found only one book that was helpful for a beginner: it was called C For Yourself, and was actually one of the manuals for the long-extinct Microsoft QuickC compiler. That book is now impossible to find, so I’ve always had to tell people that the best book for learning C as a beginner is ‘C For Yourself, but you won’t be able to find a copy!’

Writing An Introduction to C & GUI Programming

When I embarked on this project, the editor of The MagPi and I were discussing possible series for the magazine, and we thought about creating a guide to writing GUI applications in C — that’s what I do in my day job at Raspberry Pi, so it seemed a logical place to start. We realised that the reader would need to know C to benefit from the series, and they wouldn’t be able to find a copy of C For Yourself. We decided that I ought to solve that problem first, so I wrote the original beginners’ guide to C series for The MagPi.

(At this point, I should stress that the series is aimed at absolute beginners. I freely admit that I have simplified parts of the language so that the reader does not have to absorb as much in one go. So yes, I do know about returning a success/fail code from a program, but beginners really don’t need to learn about that in the first chapter — especially when many will never need to write a program which does it. That’s why it isn’t explained until Chapter 9.)

An Introduction to C and GUI programming by Simon Long published by Raspberry Pi Press

So, the beginners’ guide to C came first, and I have now got round to writing the second part, which was what I’d planned to write all along. The section on GUIs describes how to write applications using the GTK toolkit, which is used for most of the Raspberry Pi Desktop and its associated applications. GTK is very powerful, and allows you to write rich graphical user interfaces with relatively few lines of code, but it’s not the most intuitive for beginners. (Much like C itself!) The book walks you through the basics of creating a window, putting widgets on it, and making the widgets do useful things, and gets you to the point where you know enough to be able to write an application like the ones I have written for the Raspberry Pi Desktop.

An Introduction to C and GUI programming by Simon Long published by Raspberry Pi Press

It then seemed logical to bring the two parts together in a single volume, so that someone with no experience of C has enough information to go from a standing start to writing useful desktop applications.

I hope that I’ve achieved that and if nothing else, I hope that I’ve written a book which is a bit more approachable for beginners than K&R!

Get An Introduction to C & GUI Programming today!

An Introduction to C & GUI Programming is available today from the Raspberry Pi Press online store, or as a free download here. You can also pick up a copy from the Raspberry Pi Store in Cambridge, or ask your local bookstore if they have it in stock or can order it in for you.

Alex interjects to state the obvious: Basically, what we’re saying here is that there’s no reason for you not to read Simon’s book. Oh, and it feels really nice too.

59 comments

Avatar

Really bad decision to base this on GTK2 when GTK3 has been stable for a couple of years now.

Avatar

I agree with that. It’s probably because LXDE is GTK2. What happened to the Wayland based desktop that the foundation were planning. Book is a good idea, but I would have liked to have seen some real world projects. rather then making a button, making a text box etc.

Avatar

For some value of “stable” – it still seems to change enough to mean I need to tweak things whenever a new release of GTK3 appears.

GTK2 didn’t become obsolete or stop working overnight – and it is *actually* stable, as in “doesn’t change any more”.

In all seriousness, the differences between GTK2 and GTK3 in terms of the code I show in the book are few and far between – Boxes vs HBoxes and Vboxes are about the only significant one. Anyone who wants to use GTK3 will still find plenty of useful material in here.

Avatar

But shouldn’t we be training our young people for the future? Every project which I’m aware of is moving to GTK3. XFCE & Mate for example. I appreciate the changes you mentioned, but couldn’t you have said tested with version 3.x.x?

Avatar

There is always going to be some new and shiny thing that is “the future.” The future never seems to actually get here though because somewhere along the way, some other new and shiny thing becomes “the future.”

It is far more important for someone to learn how to do things in general than it is that they learn a specific implementation of those concepts. Someone who understands C will be able to use that knowledge in any context. Languages that are derived from C will be much easier to master.

Likewise, someone who understands event driven programming and the creation of GUI elements using GTK2 will be able to apply that understanding to other systems. The the time to master Qt or WxWidgets or what have you will be much, much shorter. It isn’t possible to predict what toolkit someone is going to be using any more than it is possible to predict what language someone is going to be coding in. So pick something, in this case the C language and the GKT2 GUI toolkit, and use them to teach the concepts, knowing full well that most of the people learning from you will be applying those skills in other areas.

Avatar

We are going to have to agree to disagree Lee. To me its look teaching someone Python 2 now. Anyway I hope the book does well.

Avatar

Thank you, Lee – it’s hugely rewarding when someone understands what one is trying to achieve!

The aim, as you quite rightly point out, is to teach the concepts – the basic skills, once learnt on one toolkit, will be transferable to others. This book is not intended as an encyclopaedic course in GTK; it’s an introduction (as the title says) to the concepts of GUI programming, with GTK2 as the chosen example.

Avatar

A tenner is a bargain price for a programming tutorial, so making it available as a free download is very generous. I will pick up a copy to support the cause.

Avatar

Thank you. Do let us know what you think.

Avatar

Thank you for this, Simon. I look forward to getting my hands on a copy. I think that it is a tremendously valuable contribution and feel that the disciplines and principles of programming are transferable, so any small changes in syntax aren’t the main ‘thing’ anyway. Great work indeed!

Avatar

I wrote a GTK2 program in Perl and C#: https://github.com/mobluse/gtk2-pocketcalc

It is a programmable pocket calculator, but the C# version is unfinished. I wrote it during the summer of 2015, but then I got a job and have not had time to continue yet. The Perl version works, but could use a better GUI for programming it. It was my first C# program.

Avatar

I just found 3 copies of C for Yourself on Amazon starting at $20…

And then there were 2 copies on Amazon :)

Avatar

The book looks very nice. I’ve been a software developer for over 30 years, having started with Pascal and then C in the early 80s, and mostly Java for the past 20. I think I’ll work through some of the examples from the book to get better acquainted with C on the Pi as well as GTK.

What did you use to format the manuscript?

Avatar

Hey there, there’s a typo on page 26.

“you can have multiple increments in a for loop, also separated by commas – for (a = 0; b = 1; ; a++, b *= 2). This is useful if there are two or more variables that change”

You meant to put a comma separating the declarations not a semicolon.

Avatar

Well spotted! We’ll fix that for the next printing. (We did get it right on the previous page…)

Avatar

Sounds remarkably similar to my experience at CCL as a gap year student in the late 2000s.. I wonder who gave you K&R and if it was the same person that gave it to me!

Avatar

If it was the late 2000s, probably not the same person, as they’d left by then – but I’m glad to hear CCL are keeping the tradition alive!

Avatar

There’s also a typo in the Chapter 8 line of the table of contents: “Chapter 8: The string l;ibrary”.

Fantastic book, I’m really enjoying it and finding it really easy to read, so great work!

Avatar

Trying to learn GUI programing for PI using C for my current Pi project…. And along came the book I needed!

Excellent timing. I have been using the ‘C for Yourself’ book (from a work project years ago using the QuickC compiler) to refresh my memory of C. I also use the “Microsoft C Run-Time Library” reference book by Kris Jamsa (ISBN 1-55615-227-2), again based on QuickC. Helps me remember the C programming but not to learn the GUI bit.

Avatar

Can I follow along using a regular desktop Ubuntu installation rather than raspberry pi?

Avatar

Yes, there’s nothing Pi-specific about the book – you’ll just need to make sure you have a C compiler and the GTK libraries installed on whatever computer you use. Instructions for installing GTK from apt are included in the book, so if you have a compiler, you’re all set.

Avatar

Is this just C or the newer, better C Plus Plus?

Avatar

Just C.

And there are those of us (including the author) who feel very strongly that the “++” at the end of “C++” indicates “more complicated”, not “better”…;)

If you want a book about C++, I wouldn’t even pretend to be the person to write it for you!

Avatar

£10…165 illustrated pages?
#shutupandtakemymoney
I just bought this book hoping this community continues its wonderful work.

Avatar

At long last, the awaited book! Thank you.
Thank you for writing it in C, instead of C++.
Thank you for keeping it simple.
Thank you for making it in ebook format and free!

I’ve been looking for an excuse to go back to programming. I’ll be giving this one a shot!

Avatar

Just a gentle nudge:
P11. I’d reserve printf for formatting with variables. Otherwise, I’d use puts.

P26. Unsigned int is better here?

P34. I’d add pointer to function. Such as one used by qsort.

P44. Ahaha. For loops? Ends with *(dst++)=0, maybe?

P47. For (inits; *p1==*p2;incs) if (*p1==0) return 0;
return *p1-*p2;
Although, admittedly not really for beginners anymore.

P52. Change input to name? See page 53.

P58. You don’t want to open a text file in binary mode unless you want to handle different newlines across various OSs yourself.

P72. Perhaps a more descriptive output is better. See p19.

So far, I like it very much. It does what it aims to do: A gentle introduction to C computer programming. I’ll stop here for now since GTK is a whole new territory for me, which demands intense study. Still, I’ve learned (learnt?) a thing or two. Thank you very much!

Avatar
Avatar

£10 is a bargain. Bought and paid for. As for GTK2 vs GTK3, once one has got to grips with GTK2, developing for GTK3 or any other framework is fairly straightforward with the right documentation.

Avatar

re pg 83
g_signal_connect (btn, “clicked”, G_CALLBACK (end_program), NULL);
should be…
g_signal_connect (btn, (“clicked”), G_CALLBACK (end_program), NULL);

Took me a minute to figure out what I’d done wrong. So far great though. Lot simpler window creation than my first attempts using c++ in Win95 back when. Thanks. I’ll be buying hard copy to help support the cause come payday. :-)

Avatar

re pg 84
I have had to make the same change here as well to get the code to function….
from
g_signal_connect (win, “delete_event”, G_CALLBACK (end_program), NULL);
to
g_signal_connect (win, (“delete_event”), G_CALLBACK (end_program), NULL);

Raspberry Pi 3+ w/ Raspbian Stretch with desktop and recommended software apt-get updated/upgraded this morning. Looking forward in your text I see your original without () added as I have shown here and in my previous comment. Pg 85,87,89,95….. Have I an issue? I’m no software engineer, more of a hack.

Avatar

Hmmm. I can’t see why you would need brackets there – I don’t when I run it; that parameter is just a text string. Are you using the Raspbian versions of gcc and GTK?

When you say “to get the code to function”, do you mean to get it to build, or to get it to run correctly?

Avatar

Nice! Added this and your other RPI C book to the OER-based CS curriculum I’m collating over at https://github.com/HolmSchool/HolmSchool Thanks for open sourcing your C books!

Avatar

I finished reading the book. Very good. The only thing is that p150-154 is blank. I wonder if I’m missing something? Perhaps a GTK2 reference, like the C reference on previous pages?

Avatar

Those pages are intentionally blank!

Avatar

Hi Simon,

your book is excellent, it is simple to follow the examples and the explanation of each example is very clear.
I have a slight problem, I am now up to the GTK part of the book and have an error that I don’t know how to fix.

I have set up a new folder called /home/pi/c and keep all of the code there.
I typed in the first gtk example but when I compile it i get the following error message.

gtk01.c:1:21: fatal error: gtk/gtk.h: No such file or directory
#include

Any ideas how I can fix this please.

Avatar

Make sure you have installed the GTK developer libraries – the instructions are at the bottom of page 78.

Avatar

Hi,
I ran the pkg-config command and that worked so I then ran the command
gcc `pkg-config –cflags –libs gtk+-2.0` gtkt01.c

and got the following error.
gcc: error: gtkt01.c: No such file or directory

I eventually realised that gtktest.c was referring to the program on page 77 which I had called gtk01.c once I changed the gcc command to reference gtk01.c it worked.

Thanks for your help.

Avatar

sorry that should have been gtktest.c, the command I posted was a typo on my part

Avatar

On page 31 the following lines failed for me with gcc v7:

printf(“Value of ptr_to_a is %d\n”, ptr_to_a);

Error: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’

printf(“The address of a is %d\n”, &a);

Error: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’

Avatar

I suspect you have warnings = errors set somewhere in your default compiler options – those should be warnings and not errors. While the compiler is strictly speaking correct that the values being printed are pointers to integers, those pointers are in effect just big numbers, and they should display quite happily with a %d format specifier. You could try using %ld (to tell it they are long integers) or %p (to tell it they are pointers), but I don’t think I’ve ever seen a compiler fail to print an address with a %d specifier myself.

Avatar

I do like the book very much but am having a problem with Glade

On my Raspberry Pi 2 I have installed gtk2 and Glade 3.18.3, is this a valid pair?

This version of Glade has a slightly different appearance to the one on page 136. Instead of the Hbox and the Vbox in the containers section I just have on box which is a GtkBox. I used this in the programme on page 141 and that compiled and linked successfully. However at run time I got a message testglade:9568): Gtk-CRITICAL **: IA__gtk_widget_show_all: assertion ‘GTK_IS_WIDGET (widget)’ failed.

Any help would be much appreciated

Avatar

Have you checked in Glade that your button and label widgets have the names ‘button1’ and ‘label1’, and your
window is called ‘window1′

Searching on Google for this error it looks like it’s caused when you have a mismatch in label names in the Glade file and your source code.

Avatar

“Instead of the Hbox and the Vbox in the containers section I just have on box which is a GtkBox.”

Herein is the smoking gun – you are running the wrong version of Glade. Make sure you have installed “glade-3” and not “glade”. With GNOME’s usual logic, “glade-3” is the version of Glade for GTK2, and “glade” is the version for GTK3… See page 135 for details.

Avatar

Thanks to you both. I had suspected this was the issue but was not sure.I will try again

Avatar

Sorry to be nuisance but if I enter
sudo apt-get install glade-3
Then I get the message
“Package glade-3 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source”

I assume I am doing something very silly but what.
If this is thee wrong place to ask these questions please tell me.

Avatar

I’ve just tried installing it on a Pi running the latest Stretch image, and it installed with no problems for me. Are you using Raspbian, or some other OS? (The glade-3 package may not be available under all versions of Linux, but we host it on our server for Raspbian.)

Also make sure you have run “sudo apt update” before you try to install to make sure you are up to date with the latest state of the repository.

Avatar

I am using “Raspbian GNU/Linux 8 (jessie)”
My normal practice is to run apt-get update and upgrade before any new downloads or installs.

I have a spare USB card so I am willing to try a download of the latest version of Raspian or another OS.

The reason I am keen to make it work is that the combination of your book, Geany, GTK and Glade make the Raspberry Pi ideal for my own programming interests so many thanks for your help here.

Avatar

I suggest trying a clean Raspbian image, in that case – it is downloading and installing with no issues on a Stretch image I am running here.

Avatar

Just got everything working properly using the latest Raspian/Stretch image.

Many thanks for your help, sorry to have taken your time.

Avatar

I got the book in the mail box today in Sweden, and I ordered it on 24th of April. It looks good.

Avatar

When I graduated as an EE in 1974, the only computer language I knew was Fortran. At my job, I had to learn Cobol, Basic, and some IBM System 360 Assembler. I believe that if you dominate at least one language, you already have the mental discipline and capacity to learn another. I am working with a Raspberry Pi 3 B+ now, and I know several Unix O?S versions including Solaris, AIX, HP-UX , and Linux, so Raspian is natural for me, but I do wish to learn to code in “C” soon.

Avatar

Good to know I’m not the last one left alive who started in Fortran!

Avatar

I will use this. For things graphical I have relied on Python with Pygame, but I’ve always been more comfortable programming in C. (And I endorse your comments on C++, Simon.)

Avatar

Having problems with finding

#include
^
compilation terminated.

Here was my install:
sudo apt install geany libgtk2.0 libgtk2.0-dev
directory is:
~/projects/
thank you for considering this.

Avatar

Whoops,
finding the:
#include
file.
Sorry I left that out.

Avatar

Whew, not sure whats going on with me today.
#include

Avatar

I am including the gtk/gtk.h

Leave a Comment

Comments are closed