0%

ar, ranlib, ld issue

在網路上找了一下ranlib的用法,發現這算是歷史共業之一。
一開始的ar只是像tar一樣,負責打包所有的object file。而不用來處理linking時所需要的Archive index,這個部分交由ranlib來負責。
後來發現這兩個部份可以合而為一,再加入或更新object file的時候,一同更新所需要的Archive Index。ranlib的功用就如同ar -s,為了維持相容性而留下來。

以下是一個需要使用ranlib的例子,為了示範,使用特殊的設定,一般不會遇到這種問題。假設我們現在有個foo.o了,接著建立一個archive file。

1
$ ar rcS libTest.a foo.o

注意這邊的S選項,我們強迫不讓他產生Symbol table,現今的環境就算不加s也會產生Symbol tabl。

1
2
3
$ gcc main.c libTest.a -o main
libTest.a: could not read symbols: Archive has no index; run ranlib to add one
collect2: ld returned 1 exit status

用nm看一下libTest.a

1
2
3
4
5
$ nm -s libTest.a

foo.o:
0000000000000000 T foo

nm對-s的說明如下

When listing symbols from archive members, include the index: a mapping (stored in the archive by ar or ranlib) of which modulescontain definitions for which names.

以上的結果表示我們在archive file裡面沒有archive index的存在,這時候就該ranlib登場了

1
2
3
$ ranlib libTest.a
$ gcc test.c libTest.a -o test
$ ./test

再度用nm來看結果

1
2
3
4
5
6
$ nm -s libTest.a
Archive index:
foo in foo.o

foo.o:
0000000000000000 T foo

現在看到Archive index被成功建立了