I'm compiling some C++ code into a library. Suppose my source files are mylib.cpp and util.cpp. The code in util.cpp is used in the library implementation, but is not part of the library in the sense that code using the library cannot call it (it's not in the public headers) and should not be aware of its existence; but my_lib.cpp includes util.hpp and does rely on the compiled util.cpp object code.
Now, if I compile mylib.o and util.o, then perform:
ar qc libmylib.a mylib.o util.o
my library works just fine; but - the utility code is exposed as symbols. Thus, if I link this library with some other code, there might be clashes of double-definitions. Or that other code might inappropriately rely on symbols being available (e.g. with its own header).
How can I ensure that only the object code in mylib.o (and in util.o) "sees" the symbols from util.o, while outside code does not?
Note: I believe this question stands also for C and perhaps other compiled languages.
Here is my fallback "solution", which is actually a workaround:
I keep the public visibility, but I burden all of the code in
util.cppwith some element of naming which will make it effectively unique. For example, I may enclose those functions with anamespace mylib. Not the (demangled) symbols are allmylib::foo()(ormylib::util::foo()). They will be searched, but it is reasonable to assume they won't match anything outside of the mylib code.In addition to the hassle, this has the detriment of still allowing external code to depend on this internal utility code - if it does so intentionally.