linda baldwell
linda baldwell

Reputation: 91

How do you construct a C makefile so that it compiles the source.c file?

I have three files. main.c, graph.c, and graph.h. I know the code works without a makefile because I tested it on the onlinegbd compiler. Everything runs smoothly.

When I try to run my makefile in terminal, I get an error of:

undefined reference to "function"

Where "function" is every function I call in main that is in graph.c.

So this leads me to think I'm not compiling graph.c in my makefile.

edit I have confirmed it is the makefile. I compiled it using:

gcc -o xGraph main.c graph.c

And it ran without issue. Here is the makefile:

CC = gcc

VPATH = SRC INCLUDE

TARGET = XGraph

CFLAGS = -g -Wall

all: $(TARGET)

$(TARGET): main.o graph.o
    $(CC) main.o graph.o -o $(TARGET)

main.o: main.c graph.h
    $(CC) $(CFLAGS) main.c

graph.o: graph.c graph.h
    $(CC) $(CFLAGS) graph.c

clean:
    rm *.o *~ $(TARGET)

Upvotes: 2

Views: 103

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12708

Your simplest Makefile can be:

CFLAGS = -g -Wall

xGraph_objs = main.o graph.o

xGraph: $(xGraph_objs)
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(xGraph_objs)

main.o graph.o: graph.h

as there are implicit rules (that use the $CFLAGS variable, so you don't need to add rules to do the compilation, just to specify the extra dependencies between the objects and the header file)

The structure I use frequently for small projects is very similar to yours:

targets = xGraph
toclean = $(targets)

xGraph_deps = # no dependencies to link the executable. (E.g. creating a library needed to link this)
xGraph_objs = main.o graph.o
xGraph_libs = # no libs to specify at link time. (E.g. -lm -lX11)
xGraph_ldfl = # no flags for the linker. (E.g.  -L/usr/local/lib)
toclean += $(xGraph_objs)

all: $(targets)
clean:
    $(RM) $(toclean)

xGraph: $(xGraph_deps) $(xGraph_objs)
    $(CC) $(LDFLAGS) $(xGraph_ldfl) $(xGraph_objs) -o $@ $(xGraph_libs)

Upvotes: 1

unDeadHerbs
unDeadHerbs

Reputation: 1403

When compiling C code the first stage is to generate .o files. Pass the -c flag to gcc to do this.


main.o: main.c graph.h
    $(CC) $(CFLAGS) -c main.c

graph.o: graph.c graph.h
    $(CC) $(CFLAGS) -c graph.c

Upvotes: 5

GooseDeveloper
GooseDeveloper

Reputation: 137

In C, there are two types of undefined reference errors. The first results in an implicit declaration of function error, while the second gives your undefined reference. The first says gcc cannot find a definitition of your function. but the second means gcc sees nothing wrong with your code, then tries to link object files using ld and that crashes the code. Make sure that your source files are included in compilation and they have declarations, not just definitions. Also, providing a minimum reproducible example of your code might be helpful here.

Upvotes: 2

Related Questions