diff --git a/examples/C/sum/Makefile b/examples/C/sum/Makefile new file mode 100644 index 00000000..655afbbe --- /dev/null +++ b/examples/C/sum/Makefile @@ -0,0 +1,27 @@ +TARGET = sum + +$(TARGET).objdump: $(TARGET) + riscv64-unknown-elf-objdump -S $(TARGET) > $(TARGET).objdump + +$(TARGET): $(TARGET).c Makefile + riscv64-unknown-elf-gcc -o $(TARGET) -g -O \ + -march=rv64gc -mabi=lp64d -mcmodel=medany \ + -nostartfiles -T../common/test.ld -I../common \ + $(TARGET).c ../common/crt.S ../common/syscalls.c +# Compiler flags: +# -o $(TARGET) defines the name of the output file +# -g generates debugging symbols for gdb +# -O turns on basic optimization +# -march=rv64gc -mabi=lp64d =mcmodel=medany generates code for RV64GC with doubles and long/ptrs = 64 bits +# -nostartfiles avoids inserting standard startup files because we are using crt.s +# -T specifies the linker file +# -I specifies the include path (e.g. for util.h) +# The last line defines the C files to compile. +# crt.S is needed as our startup file to initialize the processor +# syscalls.c implements printf through the HTIF for Spike +# other flags from riscv-tests makefiles that don't seem to be important +# -ffast-math -DPREALLOCATE=1 -std=gnu99 -fno-tree-loop-distribute-patterns +# -fno-common -static -fno-builtin-printf -nostdlib -lm -lgcc + +clean: + rm -f $(TARGET) $(TARGET).objdump diff --git a/examples/C/sum/sum.c b/examples/C/sum/sum.c new file mode 100644 index 00000000..4cc30867 --- /dev/null +++ b/examples/C/sum/sum.c @@ -0,0 +1,23 @@ +// sum.C +// David_Harris@hmc.edu 24 December 2021 +// Simple illustration of compiling C code + +#include // supports printf +#include "util.h" // supports verify + +long sum(long N) { + long result, i; + result = 0; + for (i=1; i<=N; i++) { + result = result + i; + } + return result; +} + +int main(void) { + int s[1], expected[1]; + s[0] = sum(4); + printf("s = %d\n", s[0]); + expected[0] = 10; + return verify(1, s, expected); // 0 means success +} \ No newline at end of file