user5056973 user5056973 - 1 month ago 7
C Question

Makefile C Linux ERROR

I can't seem to figure out why my makefile isn't executing properly. I'm getting the following errors:

gcc hr_timer.c -o hr
gcc hr_timer.o -o hr_timer
gcc: error: hr_timer.o: No such file or directory
gcc: fatal error: no input files
compilation terminated.
make: *** [hr_timer] Error 4


Here's my makefile:

CC = gcc
CFLAGS = -pthread

all: hr_timer q2q3 process_switching thread_switching

hr_timer.o: hr_timer.c
$(CC) hr_timer.c -o hr

q2q3.o: q2q3.c
$(CC) q2q3.c -o qq

process_switching.o: process_switching.c
$(CC) process_switching.c -o pr

thread_switching.o: thread_switching.c
$(CC) thread_switching.c -o th


and here is the directory that it's in:enter image description here

All the .c files compile just fine without the makefile. Thanks!

EDIT:

new makefile:

CC = gcc
CFLAGS = -pthread

all: hr_timer q2q3 process_switching thread_switching

hr_timer.o: hr_timer.c
$(CC) hr_timer.c -o hr hr_timer.o

q2q3.o: q2q3.c
$(CC) q2q3.c -o qq q2q3.o

process_switching.o: process_switching.c
$(CC) process_switching.c -o pr process_switching.o

thread_switching.o: thread_switching.c
$(CC) $(CFLAGS) thread_switching.c -o th thread_switching.o


ERROR:

gcc hr_timer.c -o hr hr_timer.o
gcc: error: hr_timer.o: No such file or directory
make: *** [hr_timer.o] Error 1


EDIT2 (FIX):

CC = gcc
CFLAGS = -pthread

all: hr qq pr th

hr: hr_timer.c
$(CC) hr_timer.c -o hr

qq: q2q3.c
$(CC) q2q3.c -o qq

pr: process_switching.c
$(CC) process_switching.c -o pr

th: thread_switching.c
$(CC) $(CFLAGS) thread_switching.c -o th

Answer

The main problem you've got here is that you're not making the target you say you are! The rule

hr_timer.o: hr_timer.c
    $(CC) hr_timer.c -o hr

Create a object file named hr (that's what -o hr does). Instead it should be:

hr_timer.o: hr_timer.c
    $(CC) hr_timer.c -o hr_timer.o

The same goes for the rest of the targets in this file. In short, a Makefile has targets and dependencies. They follow the following syntax:

target: dependency1 dependency2 dependency3 ...
    command that makes target from the dependencies

Each rule tells make that you can make target if all of the dependencies exist, and then you execute the following command. This allows make to try and make your final executable by first making it's dependencies, and if those dependencies have dependencies, it will make those too (and etc.). But, if after executing a rule, the target listed on the left side of the colon was not made, then when it is referenced later there will be a problem, the file won't exist!

ALSO, it's worth noting that you have a variable CFLAGS defined to have -pthread. You probably want to pass that to your compiler in each rules like so:

hr_timer.o: hr_timer.c
    $(CC) hr_timer.c $(CFLAGS) -o hr_timer.o
Comments