How do libraries work when linked?

I have a libmya.so library and a libmyb.so library. The functions in libmyb.so depend on the functions in libmya.so. I also have an executable myexe, which depends on libmyb.so. When I create these libraries, in what rules should the -l options be placed?

Must be 1):

libmya.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 any other combo?

+4
source share
2 answers

I would go with option 1 (although option 2 works, I would not recommend it since then, someone who links exe should remember all the necessary transitive libraries).

However, this tip is only for creating the so file, as you do above. so files (shared objects) are โ€œsmartโ€ libraries similar to executable files, except that they donโ€™t have a core library. so files can reference other libraries (for example, executables), and when the executable refers to the so file, it automatically recursively includes the dependencies of the so file.

Therefore, the so file you create must be associated with all its dependencies.

The dumb library, such as file a (static library), is a different story; then you need to follow all the links in the executable file (option 2).

I recommend using the ldd tool to examine the dependencies of the executable and so file to find out how it works.

For an example in the real world why option 1 is better, try ldd /usr/lib/libpng.so . Note that libpng is associated with libz. If this were not the case, anyone who has ever contacted libpng would also have to reference libz. Be that as it may, you can reference libpng without even knowing that libz is involved.

+1
source

Libraries are independent of each other when you create them. This is an executable file (exe or dll), which depends on them. Libraries are simply collections of functions and / or data. They just have to be there when their contents are used by exe / dll during the link (from where it doesn't matter). Libraries are not connected (when they are created), the objects files that contain them are archived by the librarian.

Functions in one library can use a function in another library, but only with the exe / dll link time will these dependencies be eliminated (this means that both libraries must be linked).

0
source

Source: https://habr.com/ru/post/1338672/


All Articles