C语言中命名空间的实现

 

foobar.h

 1 // inclusion guard
 2 #ifndef FOOBAR_H_
 3 #define FOOBAR_H_
 4 
 5 //// long names
 6 //int foobar_some_func(int);
 7 //void foobar_other_func();
 8 int some_func(int);
 9 void other_func();
10 
11 // short names
12 #ifdef NAMESPACE foobar
13 #define some_func(...) foobar_some_func(__VA_ARGS__)
14 #define other_func(...) foobar_other_func(__VA_ARGS__)
15 #endif
16 
17 #endif

 

foobar.c

 1 #define NAMESPACE foobar
 2 
 3 #include "stdio.h"
 4 #include "foobar.h"
 5 
 6 
 7 
 8 
 9 int some_func(int a)
10 {
11     return a + 99;
12 }

 

goobar.h

 1 // inclusion guard
 2 #ifndef GOOBAR_H_
 3 #define GOOBAR_H_
 4 
 5 //// long names
 6 //int foobar_some_func(int);
 7 //void foobar_other_func();
 8 
 9 // short names
10 #ifdef NAMESPACE goobar
11 #define some_func(...) goobar_some_func(__VA_ARGS__)
12 #define other_func(...) goobar_other_func(__VA_ARGS__)
13 #endif
14 
15 #endif

 

goobar.c

 1 #define NAMESPACE goobar
 2 #include "stdio.h"
 3 #include "goobar.h"
 4 
 5 
 6 
 7 
 8 int some_func(int a)
 9 {
10     return a + 8;
11 }

 

main.c

 1 #define NAMESPACE goobar
 2 #define NAMESPACE foobar
 3 
 4 
 5 #include "stdio.h"
 6 
 7 #include "goobar.h"
 8 #include "foobar.h"
 9 
10 
11 //http://stackoverflow.com/questions/389827/namespaces-in-c
12 void main()
13 {
14     int val = goobar_some_func(12);
15     printf("value = %d\n", val);
16 
17     val = some_func(12);
18     printf("value = %d\n", val);
19 
20     return;
21 }

 

 

posted @ 2015-12-29 09:34  yasepix  阅读(3310)  评论(0编辑  收藏  举报