Skip to main content

Thread: program-wide global variable


i have program split large number of files, , number of them need access path of opened file.

right have file named 'common.hpp' , declare filename.

code:
static std::string log_file = "";
and set in 1 place in program, doesn't set in other areas. did debugging , found every file apparently has own copy of 'log_file'.

understanding of 'static' keyword allocated once when program runs. apparently isn't quite accurate... how without passing string through million functions (ie, how consistent view of 'log_file')? have declare variable 'extern' somewhere?

also, whats wrong view of 'static'?

a static global variable different static variable inside function or static member function/variable.

static global variable or static (non-member) function means object has static linkage, meaning accessible code inside current compilation unit. means it's visibility @ file-level. 'static string log_file', each time header file included in separate file, file got it's own, private variable named 'log_file'.

c-ish way asking. in c++ might consider singleton or other fancy design pattern.

code:
// foo.h #ifndef _foo_h_ #define _foo_h_ #include <string>  // allow other files access our variable const std::string& get_log_file(); #endif
code:
// foo.c #include "foo.h"  // private file static std::string log_file;  const std::string& get_log_file()  {     return log_file; }
code:
// test.c  #include "foo.h"  const std::string& log_file = get_log_file();

alternatively, put following in header file:

code:
extern std::string log_file;
and in single .c file:
code:
std::string log_file;


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk [SOLVED] program-wide global variable


Ubuntu

Comments

Popular posts from this blog

Joomla site hacked, cant see front and - Joomla! Forum - community, help and support

Christian Home School Programs - Joomla! Forum - community, help and support

Trouble with PF_OutFlag_I_USE_AUDIO and PF_CHECKOUT_LAYER_AUDIO