Reputation: 5074
I've got static library that supplies logger services, and it's linked to several sub-components in my C/C++ project.
I'd like to set the scope of global variables that defined in logger
to all those entities that are link this library (for instance, log_level
), and I wonder if change the library to dynamic would do the trick... would it ?
Upvotes: 0
Views: 909
Reputation: 4501
Your question does not make clear what you mean by "component" and "scope".
If I understand correctly, you have a single program (i.e. single executable, and single process at runtime) which includes several libraries (what you call "components") and [some of] these libraries are linked to a common logger
library. You want all these libraries to be able to set a common variable log_level
defined in the logger
library. Is my understanding correct ?
If you define the log_level
as a global variable in the source code of the logger
library (i.e. defined once outside the scope of any function), you will have access to this global variable in any other component/library linked to your program by declaring it as extern
.
@MSalters, i guess you're right, but i wanted to emphasis that if i link static library to several components in my process, it will generate separate instance of this library per each such component, and not enable sharing the global variables. – Zohar81 yesterday
No, the final linking will remove any duplicate of the same library. You may link the logger
library either only once to the program or several times to every components/libraries (that are finally linked together to the program), the same single variable log_level
will be shared among everyone.
// logger.lib : logger.h
extern int log_level;
extern void log(const char* mesg);
// logger.lib : logger.c
int log_level;
void log(const char* mesg) { /*...*/ }
// component1.lib : component1.c
#include "logger.h" // declare log_level as extern
void component1()
{
log_level = 1; // modifies log_level defined in logger.c
/* ... */
}
Another (and better) way to do quite the same thing is defining you log_level variable as static and provide some kind of accessor, such as:
// logger.lib : logger.h
extern void set_log_level(int log_level);
extern void log(const char* mesg);
// logger.lib : logger.c
static int s_log_level; // only visible to logger.c
void set_log_level(int log_level) { s_log_level = log_level; }
void log(const char* mesg) { /*...*/ }
Upvotes: 1