My goal is to write a library which exposes only a public API in C language.
Let's say I'm writing a library, and it depends on two other libraries: a.c, and b.c
Contents of a.c:
int a(void) { return 1; }
Contents of b.c:
int b(void) { return 2; }
And let's say my library is m.c and its contents are:
#include "a.h"
#include "b.h"
int m(void) {
return a() + b();
}
My goal is to hide int a(void)
and int b(void)
so that they don't pollute the global namespace. I want the only symbol to be exported to be int m(void)
. That is, if my user defines their own a
, they shouldn't get a link error:
#include "m.h"
int a(void) { // SOME OTHER FUNCTION
return 5;
}
int main(void) {
return m() + a();
// THIS WOULD CREATE A LINK ERROR,
// SINCE THERE ARE TWO `A` FUNCTIONS
// IN SYMBOL TABLE
}
The only thing that comes to mind is to define macros with the same name as a
and b
like this:
#define a internal_a
#define b internal_b
This would create name-mangled symbols, and once user has an executable, they can strip away internal dependency symbols using strip -s file.elf
Another way would be to design internal dependencies as UNIX style filter programs. However, this would require serialization, and would only work if all the internal dependencies belong to me.
Both methods are not ideal, so I'd like to see if there are any better ways to achieve this in C. I'm also not sure how C++ solves this. Most probably the symbols C++ exposes have names namespace-funcname-params
.
edit: This would be trivial if I had all my dependencies in a single file. I'd simply use static
keyword where needed. My question is specifically about multiple file libraries.
edit: Even though standard C doesn't provide a portable solution for this, the problem is still very common in programming. So, solutions might not be directly relevant with C, but more with the build tools (compiler, linker, preprocessor..)