C++ – Makefile fails with error no rule to make target

cmakefile

I'm struggling to create a working make file.

My structure

  • root/Makefile
  • root/src/main.cpp
  • root/include/

My code

# Define compiler
CC = g++

# Compiler flags
CFLAGS  = -g -Wall

# Build target executable
DIR = /src
INCLUDES = ../include
TARGET = main

all: $(TARGET)

$(TARGET): $(TARGET).cpp
    cd $(DIR) &
    $(CC) $(CFLAGS) -I $(INCLUDES) -o $(TARGET) $(TARGET).cpp

clean:
    cd $(DIR) &
    $(RM) $(TARGET)

My Error

make: *** No rule to make target main.cpp', needed bymain'. Stop.

EDIT
Inside my main.cpp I have this line at the top which is meant to be found by my Makefile: #include "pugixml.hpp"

Best Answer

I think this should work for you.

All paths are given relative to the folder the Makefile is in. That means the source folder needs to be specified for the source dependencies.

# Define compiler
CC = g++

# Compiler flags
CFLAGS  = -g -Wall

# Build target executable
SRC = src
INCLUDES = include
TARGET = main

all: $(TARGET)

$(TARGET): $(SRC)/$(TARGET).cpp
    $(CC) $(CFLAGS) -I $(INCLUDES) -o $@ $^ 

clean:
    $(RM) $(TARGET)

Use tabs (not spaces) for the commands.

$@ resolves to the target (main in this case).

$^ resolves to all of the dependencies (src/main.cpp in this case).

No need to cd into the source folder.

Related Topic