Genelia D'souza
Genelia D'souza

Reputation: 125

c static library linux

I want to make a static library and was able to make one properly by following the yolinux tutorial http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

The issue arises when i want to include a static library to make a new static library. Scenario is:

gcc -Wall -c cdbSearch.c
ar -cvq cdbSrc.a cdbSearch.o cdb.a

this successfully creates a static library named cdbSrc.a

but when I try to link this with my test program

gcc -o cdbtest cdbtest.c cdbSrc.a
cdbSrc.a(cdbSearch.o): In function `cdb_search':
cdbSearch.c:(.text+0xa2): undefined reference to `cdb_seek'
collect2: ld returned 1 exit status

it gives me an error saying that cdb_seek cant be referenced which is actually a part of cdb.a

and if I compile the test program with cdb.a it works fine but then it does not serve the purpose..

gcc -o cdbtest cdbtest.c cdbSrc.a cdb.a

and the binary is created cdbtest successfully.

is this the intended behaviour, is yes why?? and if not than what am I doing wrong..

Upvotes: 0

Views: 2109

Answers (3)

rashok
rashok

Reputation: 13474

You want to create a new static library, which should contain cdbSearch.o and all the object files in cdb.a right.

I assumed like cdb.a is having two object files, which are first.o and second.o.

ar allows to add object files to an existing static library. You can execute the below command for that.

ar r cdb.a cdbSearch.o

If a library named cdb.a presents then the above command will add the new object file cdbSearch.o into that. Or else it will create new static library cdb.a which will contains only one object file(cdbSearch.o).

Now cdb.a will contains 3 objects files(first.o, second.o and cdbSearch.o). Now you can rename the static library file name if you want, mv cdb.a cdbSrc.a.

We can delete any existing object file from a static library also by using d option. For example if you want to delete the object file second.o from cdbSrc.a you can execute the below command.

ar d cdbSrc.a second.o

Use the t option to list the object files of a static library.

ar t cdbSrc.a

Upvotes: 1

CyberDem0n
CyberDem0n

Reputation: 15056

Static library is just archive of object files. You must unpack cdb.a by using ar x

And after that, pack all unpacked objects plus cdbSearch.o into cdbSrc.a

Upvotes: 1

Jay
Jay

Reputation: 24905

Yes. It is the intended behavior. You need to link all static libraries to form a binary. Static libraries unlike shared libraries will not hold the link to other libraries.

Upvotes: 3

Related Questions