Having namespaces seems like no-brainer for most languages. But as far as I can tell, ANSI C doesn't support it. Why not? Any plans to include it in a future standard?
Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed.
No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.
So whenever the computer comes across cout, cin, endl or anything of that matter, it will read it as std::cout, std::cin or std::endl. When you don't use the std namespace, the computer will try to call cout or cin as if it weren't defined in a namespace (as most functions in your codes).
For completeness there are several ways to achieve the "benefits" you might get from namespaces, in C.
One of my favorite methods is using a structure to house a bunch of method pointers which are the interface to your library/etc..
You then use an extern instance of this structure which you initialize inside your library pointing to all your functions. This allows you to keep your names simple in your library without stepping on the clients namespace (other than the extern variable at global scope, 1 variable vs possibly hundreds of methods..)
There is some additional maintenance involved but I feel that it is minimal.
Here is an example:
/* interface.h */ struct library { const int some_value; void (*method1)(void); void (*method2)(int); /* ... */ }; extern const struct library Library; /* interface.h */ /* interface.c */ #include "interface.h" void method1(void) { ... } void method2(int arg) { ... } const struct library Library = { .method1 = method1, .method2 = method2, .some_value = 36 }; /* end interface.c */ /* client code */ #include "interface.h" int main(void) { Library.method1(); Library.method2(5); printf("%d\n", Library.some_value); return 0; } /* end */
The use of . syntax creates a strong association over the classic Library_function() Library_some_value method. There are some limitations however, for one you can't use macros as functions.
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