Skip to content

Commit

Permalink
Compile an integer to an exectuable that exits with the given number
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Sep 13, 2020
0 parents commit 0522e2d
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**/*~
**/\#*
**/*.o
**/*.s
**/a.out
/tmp*
/chibicc
12 changes: 12 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CFLAGS=-std=c11 -g -fno-common

chibicc: main.o
$(CC) -o chibicc main.o $(LDFLAGS)

test: chibicc
./test.sh

clean:
rm -f chibicc *.o *~ tmp*

.PHONY: test clean
15 changes: 15 additions & 0 deletions main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "%s: invalid number of arguments\n", argv[0]);
return 1;
}

printf(" .globl main\n");
printf("main:\n");
printf(" mov $%d, %%rax\n", atoi(argv[1]));
printf(" ret\n");
return 0;
}
22 changes: 22 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/bin/bash
assert() {
expected="$1"
input="$2"

./chibicc "$input" > tmp.s || exit
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

2 comments on commit 0522e2d

@jay51
Copy link

@jay51 jay51 commented on 0522e2d Jun 22, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vaibhavsagar
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a minor typo in your commit message, I think it should be 'executable' instead of 'exectuable'.

Please sign in to comment.