1

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
beginh
  • 1,133
  • 3
  • 26
  • 36

1 Answers1

4

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
rfreytag
  • 1,203
  • 11
  • 18
  • thank you, reusable one sounds very nice! Do you recommend any tutorial for learning how to create such more reusable makefiles? I just was able to go through basics in the makefile tutorials. – beginh Jun 28 '15 at 13:12
  • 1
    I don't really have any specific tutorial recommendations. The documentation for make itself is pretty good imo, see http://www.gnu.org/software/make/manual/make.html#Overview. I had a look around though and I think this: http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ looks good. Anyway, you can also use the example file I gave and modify it for your program – rfreytag Jun 28 '15 at 14:08