user20344863
user20344863

Reputation:

Makefile in C programing issues getting to work

CC = gcc
CFLAGS = -o 
LDFLAGS = -lm 

OBJS = stack.o main.o

a.out: $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) $(LDFLAGS)

clean: 
    rm $(OBJS) 

This is my Makefile for this C program. I have a stack.c file and a main.c file. It is generating a main.o but it will not generate stack.o like I need it to. I don't understand what I am doing wrong.

Here is what it prints out when I attempt to run the program.

gcc -o    -c -o stack.o stack.c
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'stack.o' failed
make: *** [stack.o] Error 1

I expected this program to create object files for main.c and stack.c. It only created one for main.c.

Upvotes: 0

Views: 70

Answers (1)

Mark Galeck
Mark Galeck

Reputation: 6385

So here is what is happening:

Make attempts to make a.out which is the first (default) target in your Makefile. Since a.out depends on stack.o main.o, stack.o is first and it probably does not exist, so it is trying to make that first.

There is no recipe that you provided in the makefile for stack.o. So Make applies a "default" recipe, which is something like

$(CC) $(CFLAGS) -c -o stack.o stack.c

Now here is where the trouble starts. Your $(CFLAGS) is -o.

So now the default recipe that it tries to execute is

gcc -o -c -o stack.o stack.c

Now, the compiler parses this left-to-right and says, OK, -o option says they want to make an executable program, this option looks for the following name, because there is supposed to be just one name for the program, which is -c (that is a legal name). Then it sees Then it sees the second -o and it says, OK, no, they don't, the name of the program is actually stack.o. Fine. Then it sees stack.c and compiles that to an object file (which goes fine), then it tries to load that as an executable stack.o and that is a problem because there is no main() in stack.c.

This is an exact explanation of what goes wrong.

You should now be able to figure out how to fix it so it works OK. Since you are a beginner, I will leave it for you to learn. Let me know if you can't figure it out in the comments.

Upvotes: 1

Related Questions