A bit context. Let's say I have source files, which need to end up in a static library. Let's say there are two cpp files a.cpp
and a.cpp
located in two different subdirectories. Something like this:
foo/a.h
foo/a.cpp
bar/a.h
bar/a.cpp
Their content is not clashing and is completely different. The file names are just same.
Now, when compiling I end up with two a.o
files of course.
gcc -c foo/a.cpp -o foo/a.o
gcc -c bar/a.cpp -o bar/a.o
If I create a static lib now with
ar rcs libfoobar.a foo/a.o bar/a.o
I can see both files inside the static library running nm libfoobar.a
. Seems fine.
Problem
The problem I can see is if I run the ar
command individually for foo/a.o
and bar/a.o
putting them in the same static library. Now the latter object file will overwrite the former, so when running nm libfoobar.a
I just see the latter object in the library. I'm guessing this is the case due to the same object file name.
When creating a static library with ar
, should I always combine all objects in one go or is it also fine to run ar
multiple times collecting a part of objects at a time all ending up in the same static library? For this example I can see the former works, but not the latter.
How will things work when one a.cpp
changes and the static library needs to change? Will ar
find the right a.cpp
to change in the library?
This is just a small example, but consider a large project with many files and some have the same name. If you now want to create a single library you could end up with this situation as well.
In general, is this just poor organization of how libraries are composed, how files are named or is there something else to this to make things work?
You must think about
ar
as very old file archiver. It even doesn't know anything about archiving a directory. (ar archives are flat)(man ar):
ar - create, modify, and extract from archives
man ar, option
r
:Try to run a
ar t libfoobar.a
and you will see onlya.o
files becausear
didnt store directory name in the archive.So you must name all object files putted in ar archive differently (UPD) if you want to do an update of some object files in library with ar
The
ar rcs lib.a foo/a.o bar/a.o
does a replace of a.o found in the lib.a, but it does not check added files for name collision.Other case:
ar rcs lib.a foo/a.o
andar rcs lib.a bar/a.o
will store a first a.o in archive, then secondar
will find the oldera.o
in archive and does a replace of old file.