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??
-
You're static libs are just a collection of functions you implemented. The external static dependencies must *all* be eventually resolved in the final link image. How you accomplish that (linking in all the libs, using the librarian to build super-libs, etc, is up to you). [See this question/answers](http://stackoverflow.com/questions/13128/how-to-combine-several-c-c-libraries-into-one) β WhozCraig Jun 15 '14 at 18:54
-
Short answer is yes. However if you need them and forgot, the compiler will let you know at the linking stage. Usually I just link against every static lib I might or might not use, and let the compiler work out which ones actually end up getting used in the binary. β Brandin Jun 15 '14 at 19:07
3 Answers
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.

- 60,639
- 21
- 115
- 176
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
.

- 877
- 1
- 9
- 16
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
-
As itβs currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). β Community Apr 04 '22 at 21:58