From 82171f9ec347e3d1b4b5347b6f905f9a376a35ab Mon Sep 17 00:00:00 2001 From: Rui Ueyama Date: Sat, 3 Aug 2019 11:29:50 +0900 Subject: [PATCH] Compile an integer to an exectuable that exits with the given number --- .gitignore | 5 +++++ Makefile | 12 ++++++++++++ main.c | 16 ++++++++++++++++ test.sh | 22 ++++++++++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 main.c create mode 100755 test.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b27256c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*~ +*.o +tmp* +a.out +chibicc diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9fac1d6 --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +CFLAGS=-std=c11 -g -static -fno-common + +chibicc: main.o + $(CC) -o $@ $? $(LDFLAGS) + +test: chibicc + ./test.sh + +clean: + rm -f chibicc *.o *~ tmp* + +.PHONY: test clean diff --git a/main.c b/main.c new file mode 100644 index 0000000..cae6b4f --- /dev/null +++ b/main.c @@ -0,0 +1,16 @@ +#include +#include + +int main(int argc, char **argv) { + if (argc != 2) { + fprintf(stderr, "%s: invalid number of arguments\n", argv[0]); + return 1; + } + + printf(".intel_syntax noprefix\n"); + printf(".global main\n"); + printf("main:\n"); + printf(" mov rax, %d\n", atoi(argv[1])); + printf(" ret\n"); + return 0; +} diff --git a/test.sh b/test.sh new file mode 100755 index 0000000..eb1e680 --- /dev/null +++ b/test.sh @@ -0,0 +1,22 @@ +#!/bin/bash +assert() { + expected="$1" + input="$2" + + ./chibicc "$input" > tmp.s + gcc -static -o tmp tmp.s + ./tmp + actual="$?" + + if [ "$actual" = "$expected" ]; then + echo "$input => $actual" + else + echo "$input => $expected expected, but got $actual" + exit 1 + fi +} + +assert 0 0 +assert 42 42 + +echo OK