'Linking against a static lib using many other static libs

I have generated a static lib, let's call it MyLib.a. this static library uses many other static libs, eg Lib1.a Lib2.a... When I want to use my static lib MyLib.a in an application I must link against the other libs Lib1.a and Lib2.a and include their .h files too, otherwise my application does not compile or build. Do I need to include those libraries when compiling or am I missing something when generating my static library??

c++


Solution 1:[1]

Do I need to include those libraries when compiling or am I missing something when generating my static library??

If I understand your question correctly: when compiling you only need to provide the .h file paths (using -I with gcc compile command for example). Any object or library files are not used when compiling.

When creating a static .a library file, you just need the .o files produced by compiling, which you want to include in the static library.

When linking, you need to provide the libraries (and plain .o files) needed by the output binary.

Now if you use a single command to both compile and link (so the intermediate .o files etc are handled by the compiler), then you need to provide everything for that single command.

Solution 2:[2]

Static libraries are just an archive of object files (like java's jar) you can extract and combine multiple static files into a single archive with the ar utility.

ar -x lib1.a
ar -x lib2.a
ar -x mylib.a

ar c all_libs.a  *.o

after that you only have to link against one library all_libs.a.

Solution 3:[3]

The only 'solution' I've found is to directly include the cpp/h files in the project in question in a subfolder of that project. They'll all be implicitly linked into your library.

Of course, if someone else has that library as a dependency, there will be code redundancy.

Cheers John

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hyde
Solution 2
Solution 3 John Scott