开发者

Linking a dynamic library into a static library (aka pre-linking a dynamic library)

I have a very small library that I'开发者_运维技巧d like to turn to a static library (libx.a), but this library depends on a dynamic library (liby.so). I would like to be able to "pre-link" my static library, so that libx.a would already contain reference to liby.so.

This would basically allow me not to specify the option -ly when compiling a program where -lx is present. This makes things simpler when linking against libx, especially if it depends on many shared libraries.

Is it possible ? If yes, how (assuming gcc) ?

Still if possible, if the program using libx uses liby itself, will there be some kind of funny duplication (variables I suppose) going on ?


I'm confused whether you really want to include the shared library code into the static library archive, or whether you want to just make it so linking the static library automatically creates a reference to the shared library as well.

In the former case, I know of no tools to do it, but it should be a solvable problem. You could probably make a tool to convert a .so file to a normal .o file if you spend some time reading the ELF specs, then just include the .o file in the .a archive.

In the latter case, most people solve this problem with pkg-config. Another approach, which would be rather GNU-specific, would be installing a GNU linker script instead of the raw .a file, and having the linker script reference both your static library and the required shared library.


The problem here is that your dynamic library is compiled position-independent and needs a dynamic loader to fix the internal and external references at load time. Thus you cannot explicitly link against a dynamic library. In the project I'm working on we are usually compiling static and dynamic versions of libs and this is one of the reasons.


The problem can be solved by using an intelligent build system. I can recommend using gyp. It has the option link_settings for static libraries:

{
  'targets': [
    {
      'target_name': 'x',  # will generate libx.a
      'type': 'static_library',
      'sources': [],
      'link_settings': {
        'libraries': ['-ly'],
      },
    },
    {
      'target_name': 'test',
      'type': 'executable',
      'dependencies': ['x'],
      'sources': [],
    },
  ],
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜