Namespaces in C #10
Replies: 6 comments 5 replies
-
|
Beta Was this translation helpful? Give feedback.
-
Cool! Here's a C23 version without user-defined macros: #include <stdio.h>
#include <stdlib.h>
constexpr struct {
typeof(&fopen) fopen;
typeof(&fclose) fclose;
typeof(&fprintf) fprintf;
typeof(&printf) printf;
typeof(&puts) puts;
typeof(&malloc) malloc;
typeof(&free) free;
int esuccess;
int efailure;
/*etc.*/
} std = {
/*C99 designated initializer*/
.fopen = &fopen,
.fclose = &fclose,
.fprintf = &fprintf,
.printf = &printf,
.puts = &puts,
.malloc = &malloc,
.free = &free,
.esuccess = EXIT_SUCCESS,
.efailure = EXIT_FAILURE,
/*...*/
};
int main(void) {
int x = 3;
std.printf("%d\n", x);
FILE* f = std.fopen("my_file.txt", "r");
/*^^^^ you can't have types inside structs*/
std.fprintf(f, "x = %d\n", x);
std.fclose(f);
} |
Beta Was this translation helpful? Give feedback.
-
You could also solve the types thing by storing uninitialized values of primitive types (advisably not structures directly since they could be huge behind the scenes). You could also use custom macros for additional clarity. #define NAMESPACE_typedef /* expands to nothing, just for clarity */
#define NAMESPACE_accesstype(T) typeof(T)
#define nmsptype NAMESPACE_accesstype
constexpr struct {
NAMESPACE_typedef int i32;
NAMESPACE_typedef unsigned int u32;
/* ... */
} numeric = {};
int main(void) {
nmsptype(numeric.i32) exit_code = 42;
return exit_code;
} |
Beta Was this translation helpful? Give feedback.
-
really cool to see C23 adding things like this! though your types example is quite cursed 😵 |
Beta Was this translation helpful? Give feedback.
-
I'm having way too much fun with this.. #include <stdio.h>
#define MACRO_CONCAT_(P1, P2) P1 ##P2
#define MACRO_CONCAT(P1, P2) MACRO_CONCAT_(P1, P2)
#ifdef __cplusplus
// dirty hack, won't always work, I just don't have a C23 compiler so I use a C++ one instead
# define typeof decltype
#endif
constexpr struct {
typeof(&printf) myfunc;
} my_namespace = {
.myfunc = &printf
};
#define USING_my_namespace \
constexpr auto myfunc = my_namespace.myfunc;
#define USING(NAMESPACE_IDENTIFIER) \
MACRO_CONCAT(USING_, NAMESPACE_IDENTIFIER)
int main() {
my_namespace.myfunc("Hello, world!\n");
USING(my_namespace);
myfunc("Hello, world!\n");
return 0;
} |
Beta Was this translation helpful? Give feedback.
-
Namespaces in C - Talbi's Blog
https://blog.tal.bi/posts/namespaces-in-c/
Beta Was this translation helpful? Give feedback.
All reactions