0

I have a makefile which currently builds an executable, and I am attempting to modify it to build a static library instead.

My 'all' currently looks like this:

all:
    gcc $(SRC_FILES) -o $(PRODUCT_NAME) $(LD_FLAG) $(EXTERNAL_LIBS) $(INCLUDE_ALL_DIRS)

Where SRC_FILES is built by collecting all of the c files in several subdirectories:

SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c')
SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn -name '*.c')
SRC_FILES += $(shell find $(PLATFORM_DIR)/ -name '*.c')
SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c')

So I understand that in order to build a static library (.a), I will have to replace this with two steps:

  1. create object files from each of the source files

  2. create an archive (using the ar command)

My question is, what is the simplest way to do this? The examples I have seen online, for example this one have a separate call to gcc for each object file.

Ideally I would like to be able to do something like this:

gcc $(SRC_FILES) ...
(get object files somehow)
ar rvs libfoo.a $(OBJ_FILES)

What is the best way to achieve this?

sak
  • 2,612
  • 24
  • 55
  • This is really a question about how to call the compiler correctly than how to do that from a `Makefile` in particular, and obviously depends on the platform as well as somewhat on the compiler. – tripleee Feb 07 '20 at 16:05

1 Answers1

2

You need to build all source files into object files, and then add the object files to the archive.

For this I suggest you use the implicit rules to build just about everything.

Then the makefile could be something like this:

OBJ_FILES = $(SRC_FILES:.c=.o)

libfoo.a: $(OBJ_FILES)
    ar rcs libfoo.a $(OBJ_FILES)
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621