Re: [gtk-list] Re: which way is better?



On Thu, 18 Nov 1999, Matthew D Allen wrote:

> 
> >be better to use global variables for Gtk widgets, and have all
> >functions in that file use them, or create separate widgets for each
> >function?
> 
> Well, if it's a quick program that isn't going to get big, global is ok
> but it's not really stellar coding style and doesn't scale well at all.
> In fact, it becomes an ugly mess pretty fast if you're not really careful.
> 

An alternative that I use regularly that makes a reasonable compromise is
to use file static globals.

If you compose your UI as a series of dialogs/modules/elements each with
their own file, then you can make the modules widgets global in that file
only.  You do this by declaring them static, so they don't polute the
namespace of the application.  If you need to access specific widgets
between different modules you can either provide an access function
(static only affects the symbol visibility, not the address space of the
variable) or you can make specific variables global.  The former is
preferable, but a little more effort.  If you do chose to use selected
global variables DO make sure you prefix their names with the module's
prefix.

So, using access functions you have :

dialog1.h:
GtkWidget *dia1GetButton();

dialog1.c:
static GtkWidget *button;
GtkWidget *dia1GetButton() { return button; }

dialog2.h:
GtkWidget *dia2GetButton();

dialog2.c:
static GtkWidget *button;
GtkWidget *dia2GetButton() { return button; }

Using selected global variables you have :

dialog1.h
extern GtkWidget *dia1Button;

dialog1.c
GtkWidget *dia1Button;

dialog2.h
extern GtkWidget *dia2Button;

dialog2.c
GtkWidget *dia2Button;

There are other methods, but these two are the simplest, and simple is
good until your project out grows them.

A third method worth mentioning is that taken by glade.  Here you maintain
your own symbol table mapping between text strings and widget pointers.
Each widget is registered with the symbol table on creation, and contains
a pointer to the table as user_data.  The result is that, given a pointer
to any widget in the application you can obtain the widget pointer to any
widget whose name you know.  This should probably have some sort of
scoping added to it, but it is definately a useful alternative to the
previously discussed methods in many cases.

Anyway I hope this helps.

Andrae Muys

--
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Andrae Muys <andrae@humbug.org.au> "Never ascribe to malice that which is
System Programmer                   adequately explained by incompetence."
The Centre for Magnetic Resonance                   -Napoleon Bonaparte
The University of Queensland



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]