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.
util.cpp
(as well asutil.hpp
) into the source formylib.cpp
(#include "util.cpp"
) with appropriate namespace controls so that the code is available insidemylib.cpp
but not outside (anonymous namespace, ornamespace mylib::Private
or some such scheme). This is not particularly conventional, but it is probably effective (once you've worked out the necessary tweaks). The chances are that the combination TU (translation unit) is not so big as to cause your compiler major problems. This doesn't rely on compiler extensions.