By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,837 Members | 1,842 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,837 IT Pros & Developers. It's quick & easy.

How to avoid global variables and extern.

P: n/a
I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

....
gsl_rng * r;
....
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

I'm wondering if there is a better way to solve the problem in c++. I
also would like to toggle any explicit dependence in my code to the
gsl. This prompted the creation of a wrapper class like:

class RandomNumberGenerator
{
private:
gsl_rng* r;

public:

RandomNumberGenerator() ;

double generateUniform();

};

Then I would like to have something like a unique object of this class
available everywhere that does not need to be initilized (static?)
Is it possible to accomplish this task?
Do you have some better solutions to propose?
Thank you in advance for any help.

StephQ

Apr 26 '07 #1
Share this Question
Share on Google+
18 Replies


P: n/a

"StephQ" <as*******@mailinator.comwrote in message
news:11**********************@s33g2000prh.googlegr oups.com...
I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...
gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)
How about defining r as a global variable, then declaring it as extern in
just *one* header file, and simply including that header in any
implementation file which needs to use r?

(Bad name, "r", though. Something more descriptive of its purpose, and less
likely to have a name clash with local variables, would be better.)

-Howard
Apr 26 '07 #2

P: n/a
On Thu, 26 Apr 2007 18:11:54 GMT, "Howard" wrote:
>"StephQ" wrote:
>gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:
1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

How about defining r as a global variable, then declaring it as extern in
just *one* header file, and simply including that header in any
implementation file which needs to use r?
Non-const global variables have severe drawbacks and are usually not
considered good style. Since the variable is needed to '"represent"
the iteration of the random number generator algorithm' I don't think
it's a 'burden' to pass it to functions.
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 26 '07 #3

P: n/a
Roland Pibinger wrote:
On Thu, 26 Apr 2007 18:11:54 GMT, "Howard" wrote:
>"StephQ" wrote:
>>gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:
1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)
How about defining r as a global variable, then declaring it as extern in
just *one* header file, and simply including that header in any
implementation file which needs to use r?

Non-const global variables have severe drawbacks and are usually not
considered good style. Since the variable is needed to '"represent"
the iteration of the random number generator algorithm' I don't think
it's a 'burden' to pass it to functions.

I second that.

For classes at the "application" level, I usually practice passing
around an "environment" class that contains resources such as a
preferences manager, logging manager and anything else like this.

In the Austria C++ alpha (http://netcabletv.org/public_releases/) there
is an Environment (at_env.h) template which does just that.
Apr 26 '07 #4

P: n/a

On 4/26/07 11:03 AM, in article
11**********************@s33g2000prh.googlegroups. com, "StephQ"
<as*******@mailinator.comwrote:
I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...

gsl_rng * r;
...

double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)
Why not implement a function that wraps the library routine:

double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}

Greg

Apr 27 '07 #5

P: n/a
"StephQ" <as*******@mailinator.comwrote in message
news:11**********************@s33g2000prh.googlegr oups.com...
I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...
gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

I'm wondering if there is a better way to solve the problem in c++. I
also would like to toggle any explicit dependence in my code to the
gsl. This prompted the creation of a wrapper class like:

class RandomNumberGenerator
{
private:
gsl_rng* r;

public:

RandomNumberGenerator() ;

double generateUniform();

};

Then I would like to have something like a unique object of this class
available everywhere that does not need to be initilized (static?)
Is it possible to accomplish this task?
Do you have some better solutions to propose?
Thank you in advance for any help.
class RandomNumberGenerator
{
public:
double GenerateUniform() { return gsl_rng_uniform (&Seed) };
private:
static gsl_rng Seed;
};

gsl_rng RandomNumberGenerator::Seed = 0;

Notice, Seed is declared as an instance, not as a pointer. gsl_rng_uniform
needs the address of the variable which is accomplished by passing the
address of seed. In your sample you never allocated storage for r.
Apr 27 '07 #6

P: n/a
"Greg Herlihy" <gr****@pacbell.netwrote in message
news:C2******************@pacbell.net...
>
On 4/26/07 11:03 AM, in article
11**********************@s33g2000prh.googlegroups. com, "StephQ"
<as*******@mailinator.comwrote:
>I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...

gsl_rng * r;
...

double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

Why not implement a function that wraps the library routine:

double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}
Yes, this would work better than a class, IMO. Just have a static variable
in a function. Of course it should probably be:

double GenerateRandomNumber()
{
static gsl_rng r = 0;
return gsl_rng_uniform(&r);
}

or whatever you initialize gsl_rng with.
Apr 27 '07 #7

P: n/a
Jim Langston wrote:
"StephQ" <as*******@mailinator.comwrote in message
news:11**********************@s33g2000prh.googlegr oups.com...
>I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...
gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

I'm wondering if there is a better way to solve the problem in c++. I
also would like to toggle any explicit dependence in my code to the
gsl. This prompted the creation of a wrapper class like:

class RandomNumberGenerator
{
private:
gsl_rng* r;

public:

RandomNumberGenerator() ;

double generateUniform();

};

Then I would like to have something like a unique object of this class
available everywhere that does not need to be initilized (static?)
Is it possible to accomplish this task?
Do you have some better solutions to propose?
Thank you in advance for any help.

class RandomNumberGenerator
{
public:
double GenerateUniform() { return gsl_rng_uniform (&Seed) };
Would it be better to make this static as well? Then you wouldn't have
to create objects of this class.
private:
static gsl_rng Seed;
};

gsl_rng RandomNumberGenerator::Seed = 0;

Notice, Seed is declared as an instance, not as a pointer. gsl_rng_uniform
needs the address of the variable which is accomplished by passing the
address of seed. In your sample you never allocated storage for r.

Apr 27 '07 #8

P: n/a
class RandomNumberGenerator
{
public:
double GenerateUniform() { return gsl_rng_uniform (&Seed) };

Would it be better to make this static as well? Then you wouldn't have
to create objects of this class.
private:
static gsl_rng Seed;
};
gsl_rng RandomNumberGenerator::Seed = 0;
Do you see any evident problem in the the following solution?

class RandomNumber
{
private:
const gsl_rng_type* T;
gsl_rng* r;

public:

RandomNumber() ;

// Uniform random number generator.
double generateUniform();

// Distributions random number generators.
double generateGaussian(double mu, double sigma);

......

};

static RandomNumber randomNumber;

I would like to avoid passing r around because:
1) it's related to the use of the gsl library. And I would like to be
felixible about the library used for random number generation.
2) in stochastic simulations too many algorithms depend on the
generations of random numbers. I would really have to pass r even to
class constructors and so on.....

p.s. I know it is not a good name, r. It was just an example from the
gsl documentation :)

Thank you
StephQ

Apr 27 '07 #9

P: n/a
StephQ wrote:
>>class RandomNumberGenerator
{
public:
double GenerateUniform() { return gsl_rng_uniform (&Seed) };
Would it be better to make this static as well? Then you wouldn't have
to create objects of this class.
>>private:
static gsl_rng Seed;
};
gsl_rng RandomNumberGenerator::Seed = 0;

Do you see any evident problem in the the following solution?

class RandomNumber
{
private:
const gsl_rng_type* T;
gsl_rng* r;

public:

RandomNumber() ;

// Uniform random number generator.
double generateUniform();

// Distributions random number generators.
double generateGaussian(double mu, double sigma);

......

};

static RandomNumber randomNumber;

I would like to avoid passing r around because:
1) it's related to the use of the gsl library. And I would like to be
felixible about the library used for random number generation.
2) in stochastic simulations too many algorithms depend on the
generations of random numbers. I would really have to pass r even to
class constructors and so on.....
So, you want to use the solution from Greg Herlihy:
double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}

Or you can put this function to a class, and declare it static, you will
not have to pass your r to constructor:
/// in the header file
class RandomNumber
{
public:
static double generate();
}

/// in the cpp file
double RandomNumber::generate()
{
static gsl_rng * r = NULL;
return gsl_rng_uniform( r );
}

You can call it like:
RandomNumber::generate()
from any file including RandomNumber header file
Apr 27 '07 #10

P: n/a
So, you want to use the solution from Greg Herlihy:
double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}

The problem with this soulution is that r needs to be initilized only
once , by
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
I should not touch it anymore (it is automatically modified when I
call gsl_rng_uniform (r))
Or you can put this function to a class, and declare it static, you will
not have to pass your r to constructor:
/// in the header file
class RandomNumber
{
public:
static double generate();

}

/// in the cpp file
double RandomNumber::generate()
{
static gsl_rng * r = NULL;
return gsl_rng_uniform( r );

}
But I still have to create the class RandomNumber and pass it around?
Or am I missing something?

I'm doing something different. I'm creating a static class that gets
initilized at compile time.
There is no static variable in the class and no static function. It's
the class that is static.
And it's declared in the header.

I use it like:

#include <randomnumber.hpp>
......
double u = randomNumber.generateUniform(); //not RandomNumber. ....

I'm just wondering if this is considered a bad solution for reasons
that I'm missing.
In particular, this code should end up inside a dll library.
Would there be any problem with these? Will I be able to access the
static RandomNumber randomNumber from a C++ source file linked to the
dll library?

To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around

Regards
StephQ

Apr 27 '07 #11

P: n/a
On Apr 27, 2:11 pm, StephQ <askmeo...@mailinator.comwrote:
So, you want to use the solution from Greg Herlihy:
double GenerateRandomNumber()
{
static gsl_rng * r = NULL;
return gsl_rng_uniform( r);
}

The problem with this soulution is that r needs to be initilized only
once , by
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
I should not touch it anymore (it is automatically modified when I
call gsl_rng_uniform (r))
Thinking again about it I may have said something stupid :)
r , beeing a static variable, gets initilized at runtime and not every
time I call the function right?

I still get the problem that r is also used by other functions (that
generate random numbers from other distributions).

StephQ

Apr 27 '07 #12

P: n/a
StephQ wrote:
To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around
Take a look at c++ static member function.

http://www.google.de/search?hl=en&q=...=Google+Search

Apr 27 '07 #13

P: n/a
On Apr 27, 4:07 pm, anon <a...@no.nowrote:
StephQ wrote:
To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around

Take a look at c++ static member function.

http://www.google.de/search?hl=en&q=...er&btnG=Google...
I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:

* define a "normal" class and make a static instantation of it
* define a class with static member data and static member functions

The only difference I see is that using the first approach I can
instantiate other objects of the class.
Not sure if it is too useful.....

StephQ

Apr 27 '07 #14

P: n/a
StephQ wrote:
On Apr 27, 4:07 pm, anon <a...@no.nowrote:
>StephQ wrote:
>>To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around
Take a look at c++ static member function.

http://www.google.de/search?hl=en&q=...er&btnG=Google...

I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:

* define a "normal" class and make a static instantation of it
.... and go back to global variables and extern ;)
* define a class with static member data and static member functions

The only difference I see is that using the first approach I can
instantiate other objects of the class.
Try to make classes and objects as small and simple as possible
Apr 27 '07 #15

P: n/a
On Apr 27, 5:06 pm, anon <a...@no.nowrote:
StephQ wrote:
On Apr 27, 4:07 pm, anon <a...@no.nowrote:
StephQ wrote:
To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around
Take a look at c++ static member function.
>http://www.google.de/search?hl=en&q=...er&btnG=Google...
I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:
* define a "normal" class and make a static instantation of it

... and go back to global variables and extern ;)
* define a class with static member data and static member functions
The only difference I see is that using the first approach I can
instantiate other objects of the class.

Try to make classes and objects as small and simple as possible
OK

StephQ

Apr 27 '07 #16

P: n/a
"StephQ" <as*******@mailinator.comwrote in message
news:11**********************@o40g2000prh.googlegr oups.com...
On Apr 27, 4:07 pm, anon <a...@no.nowrote:
>StephQ wrote:
To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around

Take a look at c++ static member function.

http://www.google.de/search?hl=en&q=...er&btnG=Google...

I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:

* define a "normal" class and make a static instantation of it
* define a class with static member data and static member functions

The only difference I see is that using the first approach I can
instantiate other objects of the class.
Not sure if it is too useful.....
If you have other functions that use r then why not wrap them all in the
class with static methods? As for having to instantize r, the I would do a
check in the functions. Peudo code:

class Randomize
{
public:
static double RandomNumber() { if ( r == NULL ) init(); /* use r here
*/ }
static double SomeOtherMethod() { if ( r == NULL ) init(); /* use r here
*/ }
private:
static sometype* r;
static void Init()
{
if ( r = NULL )
{
gsl_rng_env_setup();
sometype T = gsl_rng_default;
r = gsl_rng_alloc (T);
}
}
};

sometype Randomize::r = NULL;
Apr 27 '07 #17

P: n/a
On Apr 27, 1:13 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
On Apr 27, 4:07 pm, anon <a...@no.nowrote:
StephQ wrote:
>http://www.google.de/search?hl=en&q=...er&btnG=Google...
I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:
* define a "normal" class and make a static instantation of it
* define a class with static member data and static member functions
The only difference I see is that using the first approach I can
instantiate other objects of the class.
Not sure if it is too useful.....

If you have other functions that use r then why not wrap them all in the
class with static methods? As for having to instantize r, the I would do a
check in the functions. Peudo code:

class Randomize
{
public:
static double RandomNumber() { if ( r == NULL ) init(); /* use r here
*/ }
static double SomeOtherMethod() { if ( r == NULL ) init(); /* use r here
*/ }
private:
static sometype* r;
static void Init()
{
if ( r = NULL )
{
gsl_rng_env_setup();
sometype T = gsl_rng_default;
r = gsl_rng_alloc (T);
}
}

};

sometype Randomize::r = NULL;
I think a namespace would be better suited than a class - since no
objects of this class are ever actually allocated. As for the issue of
accessing "r" from multiple functions - I would just encapsulate one
level deeper in the calling chaing

For example, I would suggest declaring a header file along these
lines:

// gsl.hpp

namespace gsl
{
double GetGeometricRandomNumber( double p);
double GetPoissonRandomNumber( double mu);
...
}

and then placing the corresponding implementation in a source file:

// gsl.cpp

namespace gsl
{
int * get_r()
{
static int *r = gsl_rng_alloc(gsl_rng_default);

return r;
}

double GetGeometricRandomNumber( double p)
{
return gsl_ran_geometric( get_r(), p);
}

double GetPoissonRandomNumber( double mu)
{
return gsl_ran_poisson( get_r(), mu);
}
}

Greg

Apr 28 '07 #18

P: n/a
Greg Herlihy wrote:
On Apr 27, 1:13 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
>>On Apr 27, 4:07 pm, anon <a...@no.nowrote:
StephQ wrote:
>>>http://www.google.de/search?hl=en&q=...er&btnG=Google...
I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:
* define a "normal" class and make a static instantation of it
* define a class with static member data and static member functions
The only difference I see is that using the first approach I can
instantiate other objects of the class.
Not sure if it is too useful.....
If you have other functions that use r then why not wrap them all in the
class with static methods? As for having to instantize r, the I would do a
check in the functions. Peudo code:

class Randomize
{
public:
static double RandomNumber() { if ( r == NULL ) init(); /* use r here
*/ }
static double SomeOtherMethod() { if ( r == NULL ) init(); /* use r here
*/ }
private:
static sometype* r;
static void Init()
{
if ( r = NULL )
{
gsl_rng_env_setup();
sometype T = gsl_rng_default;
r = gsl_rng_alloc (T);
}
}

};

sometype Randomize::r = NULL;

I think a namespace would be better suited than a class - since no
objects of this class are ever actually allocated. As for the issue of
accessing "r" from multiple functions - I would just encapsulate one
level deeper in the calling chaing

For example, I would suggest declaring a header file along these
lines:

// gsl.hpp

namespace gsl
{
double GetGeometricRandomNumber( double p);
double GetPoissonRandomNumber( double mu);
...
}

and then placing the corresponding implementation in a source file:

// gsl.cpp

namespace gsl
{
int * get_r()
{
static int *r = gsl_rng_alloc(gsl_rng_default);

return r;
}

double GetGeometricRandomNumber( double p)
{
return gsl_ran_geometric( get_r(), p);
}

double GetPoissonRandomNumber( double mu)
{
return gsl_ran_poisson( get_r(), mu);
}
}
Yes, namespace is also good to prevent pollution.

But to me, both solutions looks good.
Apr 30 '07 #19

This discussion thread is closed

Replies have been disabled for this discussion.