Refactoring: Add a utility function

This commit is contained in:
Rui Ueyama 2020-10-08 14:30:04 +09:00
parent 4cedda2dbe
commit 35a0bcd366
3 changed files with 22 additions and 3 deletions

View File

@ -10,6 +10,12 @@
typedef struct Type Type;
typedef struct Node Node;
//
// strings.c
//
char *format(char *fmt, ...);
//
// tokenize.c
//

View File

@ -108,9 +108,7 @@ static Obj *new_gvar(char *name, Type *ty) {
static char *new_unique_name(void) {
static int id = 0;
char *buf = calloc(1, 20);
sprintf(buf, ".L..%d", id++);
return buf;
return format(".L..%d", id++);
}
static Obj *new_anon_gvar(Type *ty) {

15
strings.c Normal file
View File

@ -0,0 +1,15 @@
#include "chibicc.h"
// Takes a printf-style format string and returns a formatted string.
char *format(char *fmt, ...) {
char *buf;
size_t buflen;
FILE *out = open_memstream(&buf, &buflen);
va_list ap;
va_start(ap, fmt);
vfprintf(out, fmt, ap);
va_end(ap);
fclose(out);
return buf;
}