开发者

How do library dependancies work when linking?

I have a library libmya.so and a library libmyb.so. The functions in libmyb.so depend on functions in libmya.so. Also I have an executable myexe which depends on libmyb.so. When I make these libraries, in which rules should I put the -l options?

Should it be 1):

li开发者_StackOverflow中文版bmya.so: $(OBJ_FILES)
    $(CPP) $(LDFLAGS) -o $@ $^

libmyb.so: $(OBJ_FILES)
    $(CPP) $(LDFLAGS) $(LIBS) -o $@ $^ -lmya

myexe: $(OBJ_FILES)
    $(CPP) $(LDFLAGS) $(LIBS) -o $@ $^ -lmyb

or 2)

libmya.so: $(OBJ_FILES)
    $(CPP) $(LDFLAGS) -o $@ $^

libmyb.so: $(OBJ_FILES)
    $(CPP) $(LDFLAGS) $(LIBS) -o $@ $^

myexe: $(OBJ_FILES)
    $(CPP) $(LDFLAGS) $(LIBS) -o $@ $^ -lmya -lmyb

or some other combo?


I would go with option 1 (though option 2 works, I wouldn't recommend it since then anybody who links the exe needs to remember all the transitive libraries required).

However, this advice is only for making an so file, as you do above. so files (shared objects) are "intelligent" libraries, much like executables, except they don't have a main. so files can link to other libraries (like executables), and when an executable links to an so file, it will automatically recursively include the dependencies of the so file.

Therefore, an so file you create should be linked with all of its dependencies.

A "dumb" library, such as an a file (static library) is a different story; then you need to do all the linking in the executable (option 2).

I recommend you use the ldd tool to investigate the dependencies of both the executable and the so file to see how this works.

For a real-world example of why option 1 is better, try ldd /usr/lib/libpng.so. Note that libpng is linked with libz. If it wasn't, anybody who ever links against libpng would also need to link against libz. As it is, you can link against libpng without even knowing that libz is involved.


Libraries are not dependant of each other when you build them. It is de executable (exe or dll) that is dependant on them. Libraries are just collections of functions and/or data. They just have to be there when their contents is used by the exe/dll at link-time (from where is not important). Libraries are not linked (when building them) ,the object-files that comprise them archived by a librarian.

The functions in one library can use function in another library ,but only at link-time of an exe/dll will those depencies be resolved (that means that both libraries must be linked in).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜