So i'm trying C instead of C++ and I've met with a problem, most of libraries, have very trivial names, whether it will be a function or whatever. For example "Berkley Socket library" has function write()
which is a really trivial name and I don't think should be used, is there any way I can not pollute my entire code with it? Can I isolate included file in some kind of namespace?
-
I agree that this is a problem in C. However, if you only include header files that you actually need, it is not too much of a problem, in my experience. For example, don't include
except in C source code files that are actually using Berkeley Sockets. I'm afraid that is the only piece of advice that I can give. Maybe someone else can offer further advice. I hope that C will sometime add support for namespaces. – Andreas Wenzel Oct 06 '19 at 19:30 -
[This Stack Overflow question](https://stackoverflow.com/questions/4396140/why-doesnt-ansi-c-have-namespaces) is related, you might find some answers there. – Andreas Wenzel Oct 06 '19 at 19:44
-
Also, [this Stack Overflow question](https://stackoverflow.com/questions/6940384/how-to-deal-with-symbol-collisions-between-statically-linked-libraries) discusses problems with name collisions in C libraries. It seems that with C libraries, it is primarily the responsibility of the library to ensure that name collisions do not occur, for example by adding a common prefix to all names. – Andreas Wenzel Oct 06 '19 at 20:03
1 Answers
For the general case
No, unless you want to do some object file hacking.
If you use the function, you'll have to define a macro to its name in the source code (e.g. #define write namespace1_write
), and then you have to use objcopy
to prefix all the symbols in the object, like so:
objcopy --prefix-symbols=namespace1_ infile.o outfile.o
If you then link to the object, you can use that function. This answer goes very in-depth into how you can do this. I suggest reading it.
For your case
Probably, if you don't require POSIX functions in your application.
If you don't use the function write
and you don't include the header file that declares it, you won't have to mess with object files. The ELF format (which is commonly used in Unix nowadays) specifies that the symbols inside the main executable override the symbols in any shared shared libraries that are loaded.
However, POSIX doesn't guarantee this. You'll have to compile in strictly conforming ISO C mode for this to apply.

- 15,171
- 8
- 38
- 76
-
yes, i think it is a good answer, but not in case when it's shared lib like `sys/socket.h` – Oct 06 '19 at 20:38
-
-
-
@ishidex2 Well, in that case, then simply don't include the header file. The ELF standard specifies that the function `write` in the program itself will override the function `write` in the standard C library. – S.S. Anne Oct 06 '19 at 20:41