Natasha Levesque
Natasha Levesque

Reputation: 19

one makefile for 2 cpp programs

Hello I need to create a makefile for 2 separated cpp programs that are in one directory. I have got this code, but it's not working correctly. The .o files do not get created.Thank you

OBJS = a b
EXEC = first_run second_run

#------ constant definitions

ALL_OBJ = $(OBJS:%=%.o)

all: $(EXEC)

clean:
    $(RM) $(EXEC) $(OBJS) $(ALL_OBJ); make all

CC = g++

DO_OBJS = $(CC) -cpp -o [email protected] [email protected]; touch $@
DO_EXEC = $(CC) -s -o $@ $(ALL_OBJ)

#------ now compile

$(OBJS):    $(@:%=%.o)
        $(DO_OBJS)

$(EXEC):    $(OBJS)
        $(DO_EXEC)

Upvotes: 0

Views: 349

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409136

There are a couple of problems with your file, but the major problem seems to be that you try to link both source files to a single executable. You have to list each program and its dependencies on its own.

Try instead this simple Makefile:

SOURCES = a.cpp b.cpp
OBJECTS = $(SOURCES:%.cpp=%.o)
TARGETS = first_run second_run

LD = g++
CXX = g++
CXXFLAGS = -Wall

all: $(TARGETS)

# Special rule that tells `make` that the `clean` target isn't really
# a file that can be made
.PHONY: clean

clean:
    -rm -f $(OBJECTS)
    -rm -f $(TARGETS)

# The target `first_run` depends on the `a.o` object file
# It's this rule that links the first program
first_run: a.o
    $(LD) -o $@ $<

# The target `second_run` depends on the `b.o` object file
# It's this rule that links the second program
second_run: b.o
    $(LD) -o $@ $<

# Tells `make` that each file ending in `.o` depends on a similar
# named file but ending in `.cpp`
# It's this rule that makes the object files    
.o.cpp:

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168596

KISS:

all: first_run second_run

clean:
    rm -f first_run second_run

first_run: a.c
    $(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@

second_run: b.c
    $(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@

Upvotes: 2

Olaf Dietsche
Olaf Dietsche

Reputation: 74008

I suggest this Makefile:

EXEC = first_run second_run
OBJS_FIRST = a.o
OBJS_SECOND = b.o

all: $(EXEC)

first_run: $(OBJS_FIRST)
    $(CXX) -o $@ $(OBJS_FIRST)

second_run: $(OBJS_SECOND)
    $(CXX) -o $@ $(OBJS_SECOND)

You don't need to define the object build, since make already knows, how to do that.

Upvotes: 0

Related Questions