How to link a project to two different versions of the same C static library?

扶醉桌前 提交于 2021-01-24 09:17:33

问题


I am working on a complex C ecosystem where different packages/libraries are developed by different people.

I would like to create a new project named foobar. This project uses two libraries, the library foo and the library bar.

Unfortunately, bar does not require the same version that foo requires. Both use say so there is a conflict.

If all the packages are on Git with submodules, the foobar project cannot be built when cloned recursively because two say functions exist in different translation units. So the submodule strategy doesn't work.

My question is: how is it possible to manage one project that uses two different version of the same static library (*.a)?

Structure

          foobar
            |
       .----'----.           <---- (require)
       v         v
      foo       bar
(v1.0) |         | (v2.0)
       '-> say <-' 

The project foobar require the library foo and the library bar, both of these libraries uses the say package: foo requires version 1 and bar requires version 2.

Packages

say

// say.h
void say(char *);

foo

// foo.c
#include "say.h"

void foo(void) {
    say("I am foo");
}

bar

// bar.c
#include "say.h"

void bar(void) {
    say("I am bar");
}

foobar

// main.c
#include <stdlib.h>
#include "foo"
#include "bar"

int main() {
    foo();
    bar();
    return EXIT_SUCCESS;
}

回答1:


Linkers typically have a mode in which they perform a partial link, which resolves references that can be currently resolved and produces an object module ready for further linking instead of a finished executable file.

For example, the GCC linker ld has a -r switch that allows this. Using this switch, and possibly others, you could link foo.o with one library to make foo.partial.o and separately link bar.o with another library to make bar.partial.o. Then you could link foo.partial.o and bar.partial.o with each other, the main program, and any other libraries and object modules needed.

This can work for static libraries, where the code for each library is included in the resulting executable or object file, and the references to its symbols are fully resolved. For shared dynamic libraries, there may be problems, since dynamic libraries require references to be resolved at run time, and the linker and executable file format might or might not support the ability to distinguish symbols of the same name in different versions of one library.



来源:https://stackoverflow.com/questions/48881047/how-to-link-a-project-to-two-different-versions-of-the-same-c-static-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!