Search code examples
cmakefilestatic-libraries

Can a static C library cause filename collisions?


My static c library libmylib.a contains common file names such as array.o and linkedlist.o

If a user using my library has files with the same names (array.c and linkedlist.c) will they end up with compilation errors? Would this also be the case for shared libraries?

I tested this out with the makefile below, but I am getting no errors. Why wouldn't there be any errors when there are two array.o files when linking?

OBJECTS = array.o main.o

main: $(OBJECTS)
    gcc $(OBJECTS) -Llibs/ -lmylib -lm

array.o: array.c array.h
    gcc -c array.c

main.o: main.c
    gcc -c main.c

Solution

  • The short answer is "no". A C library will export symbols corresponding definitions in the source code and does not depend on the name of the source code files.

    The potential problem would be if array.o in the library and array.o in the user code both defined e.g. a function with the same name.

    The general rule is that if the code modules and libraries passed to the linker contain two symbols with the same name, the linker will use the one which it encounters first. Since the order of linking is normally "user code first, then libraries", this allows user code to override (and thus eclipse) definitions in the library. Since this is a "feature", the linker will not even issue a warning or error about it (see Why doesn't the linker complain of duplicate symbols? (C++, but it does not matter in this context)).

    The same feature can make one library eclipse symbols in another library so it is a good idea to avoid too generic names when writing a library. This is sometimes accomplished by giving all exported names a common prefix (e.g. mylib_get_size() instead of just get_size()).