I am developing a shared library using C++ under Linux, and I would like this library to use log4cxx for logging purposes. However, I'm not sure how to set this up. For log4cxx to work, I need to create a logger object. How can I make sure this object is created when my library is loaded?
I suspect that it will be easiest to create the logger object as a global variable and then use it from any of the source files of my library, declaring it as extern in the headers. But how can I have the logger created automatically once an application connects to the library?
I know that in DLLs for Windows, there's a thing as REASON_FOR_CALL == PROCESS_ATTACH; is there a similar thing under Linux?
Shared libraries are the most common way to manage dependencies on Linux systems. These shared resources are loaded into memory before the application starts, and when several processes require the same library, it will be loaded only once on the system. This feature saves on memory usage by the application.
To create the library file—which is actually an archive file—we will use ar . We are using the -c (create) option to create the library file, the -r (add with replace) option to add the files to the library file, and the -s (index) option to create an index of the files inside the library file.
In C++ under Linux, global variables will get constructed automatically as soon as the library is loaded. So that's probably the easiest way to go.
If you need an arbitrary function to be called when the library is loaded, use the constructor attribute for GCC:
__attribute__((constructor)) void foo(void) {
printf("library loaded!\n");
}
Constructor functions get called by the dynamic linker when a library is loaded. This is actually how C++ global initialization is implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With