问题
I'm a beginner level c programmer coming from high level languages and feeling like c is of a flat structure. Is there a sort of way to simulate packages so I can have a clean namespace without requiring prefixes.
Nested structures is one what I'm looking at.
How it works with 3rd party external libraries out there, what happens when there's a name conflict or is it sort of separate.
In case I've to build a library or a multi modular application linked with libs so each module can have a variable, function or struct names that are same as in another module.
Also what if you are linking against two third party libs (.a file etc.) who have conflicting names, how do you resolve such conflicts.
回答1:
Ok, technically no, there is no way to have namespaces in the exact same way that C++ does. Unfortunately this leads to things like SDL2, which prefixes every function with "SDL_". About resolving conflicts between external libraries, there is one solution. Let's say we have library "libfoo", which has the function
void do_foo(void *);
defined. You try to compile and link your program, but it turns out that the other library you are using, "libfu", also has this function. Now what I would do would be to create some sort of adaptor library that renamed the function with an appropriate prefix. So we would have a file "libfoo_f.h" that defines the function
void FOO_do_foo(void *);
and in "libfoo_f.c"
#include"libfoo_f.h"
#include<libfoo.h>
void FOO_do_foo(void *data)
{
do_foo(data);
}
All this function does is provide a way to access libfoo's do_foo without breaking your libraries. Honestly, I have never had to do this due to the fact that most libraries have well-structured, well-named interfaces unlikely to conflict with other libraries.
来源:https://stackoverflow.com/questions/42756562/namespace-or-packages-in-c-modules