c++ - Define a static integer in a header with default value -


how can define integer in header file each cpp file includes header have static const int id=0 while giving ability cpps redefine other value.

i tried used weak symbol couldn't make work.

here's solution uses static variables:

// log.h #ifndef log_h #define log_h #include <iostream> #define setlogid(v) static logidsetter _logidsetter(_logid, v); #define log(v) std::cout << "id: " << _logid << ": " << (v) << std::endl;  class logidsetter { public:     logidsetter(int &id, int val)     {         id = val;     } }; static int _logid = 0; #endif 

// myclass.h class myclass {     public:     myclass();     void run(void); }; 

// myclass.cpp #include "log.h" #include "myclass.h"  setlogid(42)  myclass::myclass() {     log("myclass::cons"); }  void myclass::run(void) {     log("myclass::run"); } 

// main.cpp #include "myclass.h" #include "log.h"  setlogid(1)  int main() {     myclass mc;     log("here's main");     mc.run(); } 

the log header defines static int _logid , provides macro setlogid , class idsetter. cpp file may use setlogid redefine static value. done instantiation of class idsetter along address of _logid , desired value. trick allows bypass c++'s one definition rule.

the output looks like:

id: 42: myclass::cons id: 1: here's main id: 42: myclass::run 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -