'How to link math.h library in a makefile?

i need to compile 3 files- part1.c, part2.c, and part3.c in a makefile. only part3.c needs to use the <math.h> library. Before a makefile, this is what the gcc commands will look like:

gcc -g -o part1 part1.c
gcc -g -o part2 part2.c
gcc -g -o part3 part3.c -lm

When i try to use a makefile to run the "make" command, i keep getting errors and it does not recognize any of the math functions from the math.h library.

This is what i have in my makefile so far that is not working:

CC = gcc
CFLAGS = -Wall -g

all: driver1 

clean:
    rm -f *.o driver1 

part1.o: part1.c 
    $(CC) $(CFLAGS) -c part1.c

part2.o: part2.c 
    $(CC) $(CFLAGS) -c part2.c

part3.o: part3.c 
    $(CC) $(CFLAGS) -c part3.c -lm

driver1: part1.o part2.o part3.o
    $(CC) $(CFLAGS) -o driver1 part1.o part2.o part3.o

i had tried to run the makefile i provided, but it was giving me errors. any help will be appreciated



Solution 1:[1]

part3.o does not need to link with the library although it uses its header file. You need the library when linking everything into driver1:

# ...
part3.o: part3.c 
        $(CC) $(CFLAGS) -c part3.c

driver1: part1.o part2.o part3.o
        $(CC) $(CFLAGS) -o driver1 part1.o part2.o part3.o -lm

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ted Lyngmo