Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one emulate the C++ namespace feature in a C code?

Tags:

c++

c

namespaces

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++ namespaces - 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 structs to do the job, without success (at least considering a struct with an enumerator).

like image 402
Momergil Avatar asked Aug 21 '14 17:08

Momergil


People also ask

Can I use namespace in C?

No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.

Why do we use namespace in C?

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.

How many namespaces are there in C?

The four namespaces are: Tags for a struct/union/enum. Members of struct/union (actually a separate namespace is assigned to each struct/union )

Is namespace a keyword in C?

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.


1 Answers

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);
....
like image 54
Leushenko Avatar answered Sep 29 '22 23:09

Leushenko