How do I prevent namespace collisions in a library? Let's say I have a internal library function called foo()
, that is not included in a public header, so the user doesn't know about this function. But foo()
is used across multiple files and can't be declared static.
The Problem is, if the user now creates a function called foo()
, there is an error. How do I prevent namespace collision (as the library author), without forcing the user to not use specific function names?
example.c
#include <stdio.h>
void foo() {
printf("my foo called");
}
int main() {
foo();
}
lib.c
#include <stdio.h>
void foo() {
printf("library foo() called\n");
}
output:
$ gcc -Wall -Wextra -Werror example.c example-lib.c
/usr/bin/ld: /tmp/cci3Dd3J.o: in function `foo':
example-lib.c:(.text+0x0): multiple definition of `foo'; /tmp/ccneOJjI.o:example.c:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
Edit
I now tried the following (with the same files):
$ gcc -Wall -Wextra -Werror example-lib.c -fpic -shared -o example-lib.so
$ gcc -Wall -Wextra -Werror example.c example-lib.so
And for some reason it works. Can anyone explain why?