Is it possible to build a static library, called, say, libA that:
- Contains code that calls upon classes from libB (not created by me, so I can't modify or access it);
- Will compile when put into an app that doesn't link to libB (naturally, it will crash if the code using libB's classes is called without libB, but I can get around that. I just need the app that links with libA but not libB t开发者_如何学Pythono compile.)?
Short answer, no.
Static references need to be resolved at link time - that's what static linking means.
What you could do is to build a dynamic library that statically links libB, and then dynamically link it from your application. If you prefer static linking, you could build a static library that does the dynamic linking to your dynamic-linked library.
There is a way, but it's not portable because it relies on features that are not common to all object code formats. It may also rely on knowing the name mangling rules of your compiler. Consider your other options before deciding to do this.
You can include in your library an undefined weak symbol for every libB symbol you reference. If your code is not linked against libB in the final linking step, every undefined weak symbol will be NULL. Otherwise, the undefined weak symbols will be superseded by the symbols from libB. If you're using GCC, you can use __attribute__((weak))
on symbol declarations.
精彩评论