Skip to content

Instantly share code, notes, and snippets.

@MichaelSnowden
Last active May 10, 2024 21:46
Show Gist options
  • Save MichaelSnowden/063ccfa8697f0d8f0e389cd5c602e837 to your computer and use it in GitHub Desktop.
Save MichaelSnowden/063ccfa8697f0d8f0e389cd5c602e837 to your computer and use it in GitHub Desktop.
Expand Just Macros (Not Includes) in C
BasedOnStyle: LLVM
SeparateDefinitionBlocks: Always
EmptyLineBeforeAccessModifier: LogicalBlock
gcc -xc -E -P -o temp.c <(sed -e '/#include/!b' -e 'w includes.txt' -e 'd' main.c) && cat includes.txt temp.c | clang-format > expanded.c
#include <stdio.h>
#include <stdlib.h>
typedef struct generatorCtx {
int line;
int i;
} generatorCtx;
int generator(generatorCtx *ctx, int n) {
switch (ctx->line) {
default:
ctx->i = 0;
for (; ctx->i < n; ctx->i++) {
ctx->line = 20;
return ctx->i;
case 20:
}
return -1;
}
}
int main(void) {
generatorCtx ctx;
ctx.line = 0;
for (int i = 0; i < 10; i++) {
int d = generator(&ctx, 5);
if (d < 0)
return 0;
printf("Got %d\n", d);
}
return 0;
}
#include <stdio.h>
#define coroutine(c, r, f, a, b) typedef struct f##Ctx { \
int line; \
c \
} f##Ctx; \
r f a { \
switch (ctx->line) { default: \
b \
} \
}
#define yield(x) ctx->line = __LINE__; return x; case __LINE__:
#define init(f, n) f##Ctx n; n.line = 0;
coroutine(int i;, int, generator, (generatorCtx *ctx, int n),
ctx->i = 0;
for (; ctx->i < n; ctx->i++) {
yield(ctx->i)
}
return -1;
)
int main(void) {
init(generator, ctx)
for (int i = 0; i < 10; i++) {
int d = generator(&ctx, 5);
if (d < 0)
return 0;
printf("Got %d\n", d);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment