[personal profile] codedot
This is how you convert C source code (or any other ASCII text) into strings in C using Shell.

make(1) rules:

all: verbatim.h

verbatim.h: txt2cs.sed def.h sim.c
	printf '#define %s \\\n%s\n\n' >$*.tmp \
		INDEF "$$(sed -f txt2cs.sed def.h)"
	printf '#define %s \\\n%s\n' >>$*.tmp \
		INSIM "$$(sed -f txt2cs.sed sim.c)"
	mv $*.tmp $@

clean:
	-rm -fr verbatim.h *.tmp

sed(1) script:

s/\\/\\\\/g
s/"/\\"/g
s/	/\\t/g

$!s/^\(.*\)$/	"\1\\n" \\/
$s/^\(.*\)$/	"\1\\n"/

Sample output:

#define INDEF \
	"#ifndef _DEF_H\n" \
	"#define _DEF_H\n" \
	"\n" \
	"typedef const struct {\n" \
	"\tint type, index;\n" \
	"\tconst void *aux[];\n" \
	"} inagent;\n" \
	"\n" \
	"void inpush(inagent *left, inagent *right);\n" \
	"void interact(void);\n" \
	"inagent *inaux(void *aux);\n" \
	"\n" \
	"#endif\n"

#define INSIM \
	"#include \"def.h\"\n" \
	"\n" \
	"static struct inpair {\n" \
	"\tinagent *left, *right;\n" \
	"\tstruct inpair *next;\n" \
	"} instack;\n" \
	"\n" \
	"static void oomtest(const void *ptr, const char *str)\n" \
	"{\n" \
	"\tif (!ptr) {\n" \
	"\t\tperror(str);\n" \
	"\t\texit(EXIT_FAILURE);\n" \
	"\t}\n" \
	"}\n" \
	"\n" \
	"static inagent *incpy(inagent *agent)\n" \
	"{\n" \
	"\tinagent *copy = malloc(sizeof *copy);\n" \
	"\n" \
	"\toomtest(copy, \"malloc\");\n" \
	"\n" \
	"\treturn memcpy(copy, agent, sizeof *copy);\n" \
	"}\n" \
	"\n" \
	"void inpush(inagent *left, inagent *right)\n" \
	"{\n" \
	"\tstruct inpair *pair = malloc(sizeof *pair);\n" \
	"\n" \
	"\toomtest(pair, \"malloc\");\n" \
	"\n" \
	"\tpair->left = incpy(left);\n" \
	"\tpair->right = incpy(right);\n" \
	"\tpair->next = instack;\n" \
	"\n" \
	"\tinstack = pair;\n" \
	"}\n"

https://gist.github.com/4071205

Profile

Anton Salikhmetov

November 2018

S M T W T F S
    123
45678 910
11121314151617
18192021222324
252627282930 

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Aug. 27th, 2025 06:26 pm
Powered by Dreamwidth Studios