Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ANSI C have namespaces?

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?

like image 407
Pulkit Sinha Avatar asked Dec 09 '10 08:12

Pulkit Sinha


People also ask

Why there is no namespace in C?

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.

Do namespaces exist in C?

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

Is namespace necessary in C++?

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).


1 Answers

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.

like image 131
guest Avatar answered Oct 21 '22 14:10

guest