Bobby
Bobby

Reputation: 1571

C++ makefile not linking

EXENAME = prog1    
OBJS = link.o main.o

CXX = clang++
CXXFLAGS = -Wall -Wextra

LD = clang++

all : $(EXENAME)

$(EXENAME) : $(OBJS)
    $(LD) $(OBJS) -o $(EXENAME)

main.o : link.h main.cpp 
    $(CXX) $(CXXFLAGS) main.cpp

link.o : link.h link.cpp
    $(CXX) $(CXXFLAGS) link.cpp

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

This is the make file I got but all the function in link can't be called in main. I tried many different ways doesn't work. This works

prog1: main.cpp link.h link.cpp
    clang++ -Wall -Wextra -o prog1 main.cpp link.cpp

But I suppose is not the right way to do this?

Upvotes: 0

Views: 822

Answers (1)

MadScientist
MadScientist

Reputation: 100781

It would help if you provided at least some of the errors you got (probably the first few).

Your compiler invocation for building object files is wrong. Without any other flags specified, the compiler will try to take all the input files and create an executable out of them. So this rule:

main.o : link.h main.cpp 
        $(CXX) $(CXXFLAGS) main.cpp

expands to this compilation line:

clang++ -Wall -Wextra main.cpp

The compiler will attempt to compile and link the main.cpp file (only, because that's all that's listed here) into an executable named a.out (by default).

You need to add the -c option to your compile lines if you want to build an object file rather than link a program:

main.o : link.h main.cpp 
        $(CXX) $(CXXFLAGS) -c main.cpp

Ditto for building link.o.

Even better would be to simply use make's built-in rules for compiling object files rather than writing your own; in that case your entire makefile could just be:

EXENAME = prog1    
OBJS = link.o main.o

CXX = clang++
CXXFLAGS = -Wall -Wextra

all : $(EXENAME)

$(EXENAME) : $(OBJS)
        $(CXX) $(CXXFLAGS) $(OBJS) -o $(EXENAME)

main.o : link.h
link.o : link.h

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

Upvotes: 2

Related Questions