I am having issue with Makefile that I produced. It consists of one .cpp file with main() inside and I want to create executable from it. While putting in terminal make command I get following:
g++ STutorial.o -o MyExecutable
g++: error: STutorial.o: No such file or directory
g++: fatal error: no input files
While putting first make STutorial.o (.o created) and then make get this:
g++ STutorial.o -o MyExecutable
STutorial.o: In function `main':
STutorial.cpp:(.text+0x47a): undefined reference to `alcOpenDevice'
Firstly, why make does not go from the beginning? Secondly, why this reference is undefined as if I did not include library, I did that in Makefile aswell as in STutorial.cpp file. Can you please help me out? I was reading up what could I do wrong and see no clue. (I am beginner and maybe mistake is a rookie one, I apologise in advance but cannot understand it alone) Makefile:
FLAGS += -std=c++11
CCX=g++
FLAGS +=-c -Wall #for compilation, for warning
FLAGS += -lopenal -lSDL
all: MyExecutable
MyExecutable:
$(CXX) STutorial.o -o MyExecutable
STutorial.o: STutorial.cpp
$(CXX) $(FLAGS) STutorial.cpp
Advertisement
Answer
You have a few problem in your Makefile starting with:
FLAGS +=-c -Wall #for compilation, for warning
FLAGS += -lopenal -lSDL
You are redefining the FLAGS variable here. So what you should have is a different variable for your compiler and linker flags:
CFLAGS +=-c -Wall #for compilation, for warning
LDFLAGS += -lopenal -lSDL
Now, for the sake of giving a complete answer, and not solving your immediate problem only I’ll try to show how to make the Makefile more flexible:
Start with the sources – you should have a variable for them as well; it’s useful when adding/removing source files to/from the project:
JavaScriptSOURCES = STutorial.cpp
define a variable for your object files (this will come in handy at link-time):
JavaScriptOBJ = $(SOURCES:.cpp=.o)
Compile all source files into object files:
JavaScript.cpp.o:
$(C++) $(CFLAGS) -o $@ $<
Link your binary file using the compiled object files:
JavaScript$(MyExecutable): $(OBJ)
$(C++) $(LDFLAGS) $(OBJ) -o $@
Add a clean command for completeness (removes the binary and object files):
JavaScriptclean:
$(RM) $(EXECUTABLE) $(OBJ)
Now, putting it all together:
CCX=g++
CFLAGS +=-c -Wall -std=c++11#for compilation, for warning
LDFLAGS += -lopenal -lSDL
SOURCES = STutorial.cpp
OBJ = $(SOURCES:.cpp=.o)
all: $(MyExecutable)
$(MyExecutable): $(OBJ)
$(CCX) $(LDFLAGS) $(OBJ) -o $@
.cpp.o:
$(CCx) $(CFLAGS) -o $@ $<
clean:
$(RM) $(EXECUTABLE) $(OBJ)
This should allow you to flexibly build, rebuild, clean you project.