I have never been able to find any clear, concise and complete explanations on the creation and use of libraries in C; both dynamic/shared and static.
For a couple of reasons, I would like to implement some of my C header files for a project I am working on as libraries. Each library may have a global structure acting as a namespace for static functions in the headers, and an entry function to initialize this structure.
struct mylibrary {
int (*function1)(void);
int (*function2)(void);
} mylibrary;
static int my_library_function_1 (void) {
return 1;
}
static int my_library_function_2 (void) {
return 2;
}
void entry_mylibrary (void) {
mylibrary.function1 = my_library_function_1;
mylibrary.function2 = my_library_function_2;
}
As I understand it, this should work without a problem with a static library. All I have to do is link the library and call the function entry_mylibrary
from elsewhere in my program. However, I would like my libraries to be self-initializing; that is, I want the entry function to be called when the code is loaded. As I understand it, that is the domain of shared libraries, which can declare entry points to be executed when the library is loaded.
So why don't I simply create dynamic libraries?
Well, I am worried about application security. If I am just linking a library at runtime, I don't see what is to prevent some end user from swapping my library for their own. Could I not create a new library declaring the same variables as the old one, and swap the definitions of these variables for my own? I don't see why the executable would care.
I suppose then that my questions are:
- Is there some obscure method to self-initializing a static library?
- How can I verify that the (shared) library I load is indeed MY library?
I am/will be working cross platform. 64 bit Windows and Linux. Apple products are to-be-determined, but not a priority.
I am using Visual Studio 2017 Community on Windows 10. I will be using GCC for linux. I will be implementing the same libraries on all platforms with platform compilers, e.g. VS 2017 on Windows and GCC on linux; I won't be cross-compiling platform-specific code.