Search code examples
cmakefilestatic-libraries

How to create a static library out of many .c and .h files using Makefile?


I am trying to create a static library out of Trezor Firmware's Crypto Module. I was trying to write a Makefile in order to do that, but I am not sure on how to define the order of compilation in Makefile. The make is failing for the following.

Makefile -

CC = gcc
AR = ar
CFLAGS = -Wall -Werror -pedantic

SRC_DIR = trezor-firmware/crypto
BUILD_DIR = build
LIB_DIR = lib

# List all the .c files in the source directory
SRC_FILES := $(wildcard $(SRC_DIR)/*.c)

# Derive object file names from the source file names
OBJ_FILES := $(patsubst $(SRC_DIR)/%.c,$(BUILD_DIR)/%.o,$(SRC_FILES))

# The target library name
LIB_NAME = libcrypto.a

# The final path of the library
LIB_PATH = $(LIB_DIR)/$(LIB_NAME)

# Default target
all: $(LIB_PATH)

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c $(wildcard $(SRC_DIR)/*.h)
    $(CC) $(CFLAGS) -c $< -o $@

# Rule to create the library
$(LIB_PATH): $(OBJ_FILES)
    $(AR) rcs $@ $^

# Clean build artifacts
clean:
    rm -rf $(BUILD_DIR)/*.o $(LIB_PATH)

When I execute, it throws the following error -

gcc -Wall -Werror -pedantic -c trezor-firmware/crypto/bip32.c -o build/bip32.o
In file included from trezor-firmware/crypto/bip32.h:31:0,
                 from trezor-firmware/crypto/bip32.c:32:
trezor-firmware/crypto/ed25519-donna/ed25519.h:4:21: fatal error: options.h: No such file or directory
 #include "options.h"
                     ^
compilation terminated.
make: *** [build/bip32.o] Error 1

Can someone please help me out on this?

I tried adding $(wildcard $(SRC_DIR)/*.h) so that all the header files are also taken into consideration but it didn't help. Someone I feel that this is related to dependencies of internal .c files not getting configured in the right order.


Solution

  • The error message indicates that GCC cannot find options.h. In addition to being present and readable, the file's path must be added to the compiler's include path. Effectively, this tells the compiler where to look for #include'ed files.

    In the linked project's Makefile, this is accomplished by adding the current directory with -I..

    Also see -I Flag in GCC ( Linux )