user7847084
user7847084

Reputation:

Namespacing libraries in C

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?

Upvotes: 4

Views: 330

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15576

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.

Upvotes: 1

Related Questions