ar on an existing .a file?

落爺英雄遲暮 提交于 2019-12-20 02:35:06

问题


Essentially, what I want to do is this:

gcc foo.c -o foo.o
ar rcs foo.a foo.o
gcc bar.c -o boo.o
ar rcs bar.a bar.o foo.a

I want to archive both an object and a static library into another static library. Unfortunately, the last command doesn't end up containing foo.o (it contains bar.o and foo.a), so when I get to the linking stage, the linker can't find the symbols from foo.o.

Is there a way to do what I want here? I'm doing all of this out of make, so I'm looking for a solution that doesn't involve extracting & re-archiving the objects (which seems kinda painful). Is there a way to make this kind of "archive from another archive" setup work?


回答1:


Actually, you do not want to archive one whole '.a' file inside another. You might want to archive the members of the one archive in the other - but that is a wholly different operation.

The 'ar' program is perfectly capable of storing source files, gzipped tar files, HTML files, XML files, and pretty much any other type of file in the '.a' (and the '.a' suffix is only conventional, not mandatory) -- try it some time. However, it treats object files (and only object files) specially, and makes them available for use by the linker ('ld'), but the linker only uses such files if the extension is '.a'.

So, you want to have two libraries:

  1. foo.a containing just foo.o
  2. bar.a containing bar.o and all the objects from foo.a

Short of doing as you suggest and extracting the objects from foo.a and building them into bar.a, the only alternative is to list the members of foo.a as members of bar.a too:

FOO_OBJS = foo.o
BAR_OBJS = bar.o $(FOO_OBJS)

foo.a: $(FOO_OBJS)
    $(AR) $(ARFLAGS) $@ $(FOO_OBJS)
bar.a: $(BAR_OBJS)
    $(AR) $(ARFLAGS) $@ $(BAR_OBJS)

I am assuming that your example is minimized. If it is not, then why bother with two libraries. Anything that uses just code from foo.o will only link foo.o even if given bar.a to link with. (It would be slightly different if these were shared objects, but it would probably still be better to use just one rather than two shared objects.)




回答2:


ar rcs foo.a foo.o
cp foo.a foo2.a
gcc -c bar.c
ar rs foo2.a bar.o

And perhaps use foo.a instead of foo2.a if you don't need to keep it in its original form.



来源:https://stackoverflow.com/questions/4318906/ar-on-an-existing-a-file

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