0

Here is my makefile:

CC=gcc 

CFLAGS=-g

LDFLAGS=-lm

EXECS= p1


all: $(EXECS)

clean: 
    rm -f *.o $(EXECS)

14:32:16 **** Build of configuration Default for project CH3-Programs **** make p1 gcc -g -ggdb -lm p1.c -o p1 /tmp/ccNTyUSA.o: In function main': /home/bm5788/fromVM/Workspace/CH3-Programs//p1.c:28: undefined reference topow' collect2: error: ld returned 1 exit status make: *** [p1] Error 1 : recipe for target 'p1' failed

1 Answers1

2

The problem here is the order you link with the math library (the -lm option). Libraries should be after the sources or object files on the command line when building.

So if you ran the command to build manually, it should look like

gcc p1.c -o p1 -lm

The problem is that your makefile doesn't really do anything, and it lives on implicit rules alone. The implicit rules use certain variables in a certain order which do not place the library in the right position in your makefile.

Try instead something like this makefile:

# The C compiler to use.
CC = gcc

# The C compiler flags to use.
# The -g flag is for adding debug information.
# The -Wall flag is to enable more warnings from the compiler
CFLAGS = -g -Wall

# The linker flags to use, none is okay.
LDFLAGS = 

# The libraries to link with.
LDLIBS = -lm

# Define the name of the executable you want to build.
EXEC = p1

# List the object files needed to create the executable above.
OBJECTS = p1.o

# Since this is the first rule, it's also the default rule to make
# when no target is specified. It depends only on the executable
# being built.
all: $(EXEC)

# This rule tells make that the executable being built depends on
# certain object files. This will link using $(LDFLAGS) and $(LDLIBS).
$(EXEC): $(OBJECTS)

# No rule needed for the object files. The implicit rules used
# make together with the variable defined above will make sure
# they are built with the expected flags.

# Target to clean up. Removes the executable and object files.
# This target is not really necessary but is common, and can be
# useful if special handling is needed or there are many targets
# to clean up.
clean:
    -rm -f *.o $(EXEC)

If you run make using the above makefile, the make program should first build the object file p1.o from the source file p1.c. Then is should use the p1.o object file to link the executable p1 together with the standard math library.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621