简体   繁体   中英

Struggling with a GCC Makefile

I am trying to write what I thought would be quite a simple Makefile and I'm just baffled! I'm not a makefile writer, but I thought I understood them enough to be able to get a simple one working.

Okay, I have a small project in a directory and also in this directory is a libs directory containing many .c files. What I'm trying to do is write a makefile that will build the contents of the /libs directory into a static lib file in the /libs directory and then compile a few source files in the / directory and link it against the built .a file.

I'm sure someone's going to suggest "why not use cmake", but that's not answer I'm looking for (waves hand like a Jedi.. ehehehehe)

CC = gcc
CFLAGS = -Wall
SOURCES = lzx.c csum.c dirs.c listner.c tree.c
OBJECTS = $(SOURCES:.c=.o)
TARGETLIB = libs/mylib.a
TARGET = TestApp

libs/%.o : libs/%.c
    $(CC) $CFLAGS -c $<

$(TARGETLIB) : $(OBJECTS)
    ar rcs $@ $^

$(TARGET) :
    $(CC) $CFLAGS Source1.cpp Source2.cpp -llibs/mylib.a -o $@

My understanding was that the first recipe, would compile all the .c files into objects, but it seems to compile the first .c file and then stop.

Any help anyone could give me would be appreciated.

Since Your final app is TARGET, You should make it first Makefile rule. And since it also depends on TARGETLIB it should be given as dependency, like so:

$(TARGET): $(TARGETLIB)
    $(CC) $(CFLAGS) Source1.cpp Source2.cpp -Lmylib -o $@

next I assume that *.c files You mentioned are lib files. Thus You will need a prefix to them, since You want to specify them by hand, not via wildcard or rule.

OBJECTS = $(addprefix(libs, $(SOURCES)):.c=.o)

and last thing that comes to my mind is library name, which supposed to be libSOMENAME.a (well, linker searches for this name in path and -Lotherpaths). So we have:

TARGETLIB = libs/libmylib.a

summing it all up:

CC = gcc
CFLAGS = -Wall
SOURCES = lzx.c csum.c dirs.c listner.c tree.c
OBJECTS = $(addprefix(libs, $(SOURCES)):.c=.o)
TARGETLIB = libs/libmylib.a
TARGET = TestApp

$(TARGET) : $(TARGETLIB)
    $(CC) $(CFLAGS) Source1.cpp Source2.cpp -static -L./libs -lmylib -o $@

$(TARGETLIB) : $(OBJECTS)
    ar rcs $@ $^

And yes, this could be written much better, but I assume if You wanted to learn more about Makefiles or linker, and not just shown where You made mistakes, You'd know how to find manual pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM