Reputation: 1153
I wrote makefile the way below and get undefined reference error for all functions that are stored in AM.cpp and used in main. What do i do wrong?
CCX=g++
FLAGS +=-c -Wall -lopenal -lSDL
LINK_FLAGS += -lopenal -lSDL
all: MyExe
MyExe: main.o
$(CXX) main.o $(LINK_FLAGS) -o MyExe
main.o: main.cpp AM.cpp AB.cpp AS.cpp
$(CXX) $(FLAGS) main.cpp AM.cpp AB.cpp AS.cpp
Upvotes: 1
Views: 390
Reputation: 1193
You should compile an object for every cpp you have and then in the final linking step you should name all of them.
Also the libraries only need to be specified in the linker flags.
Like so:
CCX=g++
FLAGS +=-c -Wall
LINK_FLAGS += -lopenal -lSDL
all: MyExe
MyExe: main.o AM.o AB.o AS.o
$(CXX) main.o AM.o AB.o AS.o $(LINK_FLAGS) -o MyExe
main.o: main.cpp
$(CXX) $(FLAGS) main.cpp
AM.o: AM.cpp
$(CXX) $(FLAGS) AM.cpp
AB.o: AB.cpp
$(CXX) $(FLAGS) AB.cpp
AS.o: AS.cpp
$(CXX) $(FLAGS) AS.cpp
It's also not a bad idea to just create a universal makefile that can be re-used. Mine looks like this:
CXX=gcc
CXX_FLAGS=-c -O0 -Wall -Wextra
CXX_LFLAGS=-lssl -lcrypto -ldl -liniparser
SOURCES=main.cpp test.cpp ...cpp #add your source files here
OBJECTS=$(SOURCES:.cpp=.o) #takes the .cpp files from the SOURCES var and replaces the .cpp with .o for each
EXEC=yourapp
all: $(SOURCES) $(EXEC)
clean:
rm -f $(OBJECTS)
rm -f $(EXEC)
$(EXEC): $(OBJECTS)
$(CXX) -o $@ $(OBJECTS) $(CXX_LFLAGS) #$@ will be replaced with the content of EXEC, so your applications name
#a build rule for all .cpp files to be compiled to a .o file. % is a placeholder for the actual name of the file
%.o: %.cpp
$(CXX) $(CXX_FLAGS) $< # $< will be replaced with the .cpp file name
Upvotes: 4