1# Makefile for generating and compiling an Xtensa-ESP32 ELF file that has a lot
2# (too many) sections.
3#
4# To generate the C file and compile it, simply use the following command:
5# make
6
7# Adjustable parameters
8BASH=/bin/bash
9SECTIONS_COUNT=350
10
11# Do not touch the following variables
12CC=xtensa-esp32-elf-gcc
13CFLAGS=-W -std=c99
14LDFLAGS=-nostdlib -ffunction-sections -fdata-sections
15OBJ=esp32-too-many-sections.o
16BIN=esp32-too-many-sections.elf
17SRC=esp32-too-many-sections.c
18
19# The following command will generate the C file to compile.
20# This is the simplest way to have a working and easily maintainable
21# C file as it is almost only way out repetitions.
22define generate_c_code =
23    # Generate the constants, one per section.
24    # Is it necessary to align the sections on an 16-byte bounds in order
25    # to prevent esptool to merge them while generating the binary.
26    # Indeed, by aligning them, there will be padding between them.
27    echo "Generating $(SRC) ..."
28    echo "// This has file been automatically generated, please check Makefile for\
29more information." > $(SRC); \
30    for i in {1..$(SECTIONS_COUNT)}; \
31    do \
32        echo "const int number$$i __attribute__ ((section (\".NUM$$i\"), aligned((16)))) = $$i;" >> $(SRC) ;\
33    done;
34    echo -e "\n" >> $(SRC) ; \
35    echo "int _start(void) {" >> $(SRC) ; \
36    echo "    volatile long int res =" >> $(SRC) ; \
37    for i in {1..$(SECTIONS_COUNT)}; \
38    do \
39        echo "        (unsigned int) number$$i +" >> $(SRC) ;\
40    done;
41    # Adding 0 at the end it simpler than making a special case for the last
42    # loop iteration
43    echo "        0;" >> $(SRC) ;
44    echo "    return res;" >> $(SRC) ;
45    echo "}" >> $(SRC) ;
46endef
47
48.PHONY: all clean generate-src
49
50all: $(BIN)
51
52$(BIN): $(OBJ)
53	$(CC) -o $@ $^ $(LDFLAGS)
54
55# By default, make uses sh as script language, use bash to generate the C file
56$(SRC): SHELL:=$(BASH)
57$(SRC):
58	@$(generate_c_code)
59
60%.o: %.c
61	$(CC) -c -o $@ $^ $(CFLAGS)
62
63clean:
64	rm -f $(SRC) $(BIN) $(OBJ)
65