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.