I'm developing a software which is in C++ but that communicates with a C app through a shared header file containing the communication protocol. Since C is "more basic" than C++, I always need to write the header in C code (so C++ also gets it); otherwise it wouldn't work for the second app.
The problem is that I need to use a scope-quilifier such as the C++ namespace
s - which don't exist in C.
What are all the options to emulate the namespace
feature in C?
The only possibility I have seen so far is the one shown in this SO question, but unfortunately the answer is not clear enough and I would certainly like to know if there are other options. I also tried to use struct
s to do the job, without success (at least considering a struct
with an enum
erator).
No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
The four namespaces are: Tags for a struct/union/enum. Members of struct/union (actually a separate namespace is assigned to each struct/union )
The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types.
You can hide all of your exported functions from being exported from the module with static
at the definition level, so that no names are placed in the global space, and instead put them in a struct that is the only thing provided by the module.
E.g. foo.h:
struct ns_t {
int (*a)(int, int);
void (*b)(float, float);
};
extern struct ns_t ns;
foo.c:
#include "foo.h"
static int a(int x, int y) {
...
}
static void b(float x, float y) {
...
}
struct ns_t ns = { .a = a, .b = b };
bar.c:
#include "foo.h"
....
ns.b(4.5, 6.8);
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With