Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespacing in C with structs

Tags:

c

namespaces

It is possible to imitate namespaces in C like this:

#include <stdio.h>
#include <math.h>

struct math_namespace {
    double (*sin)(double);
};
const struct math_namespace math = {sin};

int main() {    
    printf("%f\n", math.sin(3));

    return 0;
}

Are there any disadvantages to this, or just situations where a prefix makes more sense? It just seems cleaner to do it this way.

like image 600
Overv Avatar asked Oct 05 '22 21:10

Overv


1 Answers

This method is already used in real projects such as the C Containers Library by Jacob Navia. C is not designed for object-oriented programming. This is not really efficient, since you have to (1) access to the structure and (2) dereference the function pointer. If you really want prefixes, I think changing your identifiers remains the best solution.

like image 193
md5 Avatar answered Oct 10 '22 01:10

md5