Reputation: 57
I am having some trouble with a programing assignment for a CS class. We were introduced to makefiles this week, but it was barely touched upon. The goal is to write a program to calculate the average and summation of user provided doubles. The program works fine with g++, but I am having issues with the makefiles.
I am working with 3 cpp files: main.cpp, average.cpp, summation.cpp. And 2 header files: average.h and summation.h
Here is one make file I have tried:
CXX = g++
CXXFLAGS = -std=c++0x -Wall -pedantic-errors -g
SRCS = summation.cpp average.cpp main.cpp
OBJS = ${SRCS:.cpp=.o}
HEADERS = summation.h average.h
MAIN = myprog
all: ${MAIN}
@echo Simple compilter named myprog has been compiled
${MAIN}: ${OBJS} ${HEADERS}
${CXX} ${CXXFLAGS} ${OBJS} -o ${MAIN} ${OBJS}
.cpp.o:
${CXX} ${CXXFLAGS} -c $< -o $@
clean:
${RM} ${PROGS} ${OBJS} *.o *~
Errors:
main.cpp:31: undefined reference to avg(double*, int)'
main.cpp:32: undefined reference to
sum(double*, int)'
If I run the command g++ main.cpp summation.cpp average.cpp -o main Then it will compile without any issues.
I'm not sure if I have something out of order, or if I am missing something. Looking around I've found a lot of info, but it seems to be over my head.
Upvotes: 3
Views: 3318
Reputation: 2178
I think you have two problems here.
First, the ordering SRCS = summation.cpp average.cpp main.cpp
. This causes the .o
to be provided to g++ in the order summation.o average.o main.o
which causes the undefined error. You want to provide them in the order main.o summation.o average.o
, hence SRCS should be SRCS = main.cpp summation.cpp average.cpp
.
Second, in the line:
${CXX} ${CXXFLAGS} ${OBJS} -o ${MAIN} ${OBJS}
The second ${OBJS}
is not needed.
Try the following:
CXX = g++
CXXFLAGS = -std=c++0x -Wall -pedantic-errors -g
SRCS = main.cpp summation.cpp average.cpp
OBJS = ${SRCS:.cpp=.o}
HEADERS = summation.h average.h
MAIN = myprog
all: ${MAIN}
@echo Simple compilter named myprog has been compiled
${MAIN}: ${OBJS}
${CXX} ${CXXFLAGS} ${OBJS} -o ${MAIN}
.cpp.o:
${CXX} ${CXXFLAGS} -c $< -o $@
clean:
${RM} ${PROGS} ${OBJS} *.o *~.
Upvotes: 5