443,837 Members | 1,842 Online 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
18 Replies

 P: n/a "StephQ"

 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 numbergenerator algorithm, so it needs to be accessible every time you needto 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 veryelegant) How about defining r as a global variable, then declaring it as extern injust *one* header file, and simply including that header in anyimplementation 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 numbergenerator algorithm, so it needs to be accessible every time you needto 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 veryelegant) How about defining r as a global variable, then declaring it as extern injust *one* header file, and simply including that header in anyimplementation 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"

 P: n/a "StephQ"

 P: n/a "Greg Herlihy" On 4/26/07 11:03 AM, in article 11**********************@s33g2000prh.googlegroups. com, "StephQ" I'm facing the following problem: I'm using the Gnu Scientific Library(it is a C math library), and in particular random number generationalgorithms. Example code is:... gsl_rng * r;...double u = gsl_rng_uniform (r);The problem is that r "represent" the iteration of the random numbergenerator algorithm, so it needs to be accessible every time you needto 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 veryelegant) 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" I'm facing the following problem: I'm using the Gnu Scientific Library(it is a C math library), and in particular random number generationalgorithms. Example code is:...gsl_rng * r;...double u = gsl_rng_uniform (r);The problem is that r "represent" the iteration of the random numbergenerator algorithm, so it needs to be accessible every time you needto 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 veryelegant)I'm wondering if there is a better way to solve the problem in c++. Ialso would like to toggle any explicit dependence in my code to thegsl. 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 classavailable 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 haveto 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 ...... 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

 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

 P: n/a StephQ wrote: On Apr 27, 4:07 pm, anon 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 accessibleseverywhere in the program3) 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 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" 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" 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" >On Apr 27, 4:07 pm, anon >>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 functionsThe only difference I see is that using the first approach I caninstantiate 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 theclass with static methods? As for having to instantize r, the I would do acheck 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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8193802,"math_prob":0.76676804,"size":23430,"snap":"2019-51-2020-05","text_gpt3_token_len":5881,"char_repetition_ratio":0.15491335,"word_repetition_ratio":0.8375739,"special_character_ratio":0.2622706,"punctuation_ratio":0.1755575,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9797083,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-23T12:39:11Z\",\"WARC-Record-ID\":\"<urn:uuid:ddfbcc91-f251-4ed1-8470-df0cf41f9965>\",\"Content-Length\":\"82977\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:6c7f0a6e-bbd5-4475-9af1-5ec91142082d>\",\"WARC-Concurrent-To\":\"<urn:uuid:fe4e5d62-6b59-4f1d-b244-bca26959d00f>\",\"WARC-IP-Address\":\"104.197.32.212\",\"WARC-Target-URI\":\"https://bytes.com/topic/c/answers/638448-how-avoid-global-variables-extern\",\"WARC-Payload-Digest\":\"sha1:W2EKPN6XGR7OUOHFXPBSQM6I5K7HUQ4M\",\"WARC-Block-Digest\":\"sha1:64QTZHVZ5UABIQBA6KUXBEAP2N6DMH2B\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579250610004.56_warc_CC-MAIN-20200123101110-20200123130110-00210.warc.gz\"}"}