Skip to content
Advertisement

makefile linking does not work (although no error message)

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:

  1. 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:

    SOURCES = STutorial.cpp
    
  2. define a variable for your object files (this will come in handy at link-time):

    OBJ = $(SOURCES:.cpp=.o)
    
  3. Compile all source files into object files:

    .cpp.o:
        $(C++) $(CFLAGS) -o $@ $<
    
  4. Link your binary file using the compiled object files:

    $(MyExecutable): $(OBJ)
       $(C++) $(LDFLAGS) $(OBJ) -o $@ 
    
  5. Add a clean command for completeness (removes the binary and object files):

    clean:
        $(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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement