0

I am a novice user of makefile, I have created rules(run1, run2 etc) to execute c and c++ objects separately(separate compilation is successful c/c++, also need to execute them separately) but it seems not working as expected, could anyone tell were it went wrong and how to correct it

TARGET_EXEC ?=

BUILD_DIR ?= .
SRC_DIRS ?= .

SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c)
OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)

INC_DIRS := $(shell find $(SRC_DIRS) -type d)
INC_FLAGS := $(addprefix -I,$(INC_DIRS))

CC = gcc
CXX = g++
CFLAGS = -g -Wall
CPPFLAGS = -g -lws2_32 -Wno-write-strings

.PHONY: all run1 run2 run3 clean
all: $(BUILD_DIR)/$(TARGET_EXEC)

$(BUILD_DIR)/$(TARGET_EXEC): $(OBJS)
    @echo "Build completed"

# c source
$(BUILD_DIR)/%.c.o: %.c
    @echo "Compiling C sources"
    @$(CC) $(CFLAGS) $< -o $(basename $(<F))
    @echo "Compiled successfully"

# c++ source
$(BUILD_DIR)/%.cpp.o: %.cpp
    @echo "Compiling C++ sources"
    @$(CXX) -o $(basename $(<F)) $(CXXFLAGS) $< $(CPPFLAGS)
    @echo "Compiled successfully"

clean:
    @echo "Cleaning"
    @$(RM) -r *.exe
    @echo "Cleaned up"

run1: $(OBJS)
$(OBJS)=$(SRCS)
$(SRC_DIRS)/%.c.o: %.c
    @echo "from run1"
    ./$(basename $(<F)) ${ARGS}

run2: $(OBJS)
$(OBJS)=$(SRCS)
$(SRC_DIRS)/%.cpp.o: %.cpp
    @echo "from run2"
    ./$(basename $(<F)) ${ARGS}

command used: make run1

output:

    from run1
     -> execution
    from run2
     -> execution

Expected output

    from run1
--> execution of exe created

Moreover I am trying to pass arguments which I have referred from link to pass on to make run. eg:

make ARG="-p TCP -n 127.0.0.1 -e 10006 -l 1" run2 

also let me know if this can be done without any issues.

Community
  • 1
  • 1
Emman
  • 1,180
  • 1
  • 22
  • 38
  • Possible duplicate of [How to build multiple targets with similar name?](http://stackoverflow.com/questions/42662359/how-to-build-multiple-targets-with-similar-name) – jjm Mar 13 '17 at 07:25
  • I'm not seeing how that's a duplicate. It doesn't address OP's issue. – blackghost Mar 13 '17 at 13:45

1 Answers1

0

look at the rules:

run1: $(OBJS)
$(OBJS)=$(SRCS)
$(SRC_DIRS)/%.c.o: %.c
    @echo "from run1"
    ./$(basename $(<F)) ${ARGS}

The first line says run1 is dependent on $(OBJS), but does not have any explicit recipes. The next line does an assignment, and the last line defines a pattern rule for all .c.o files with some recipes. These recipes are not associated with run1. When you run make run1, it will build the dependencies ($(OBJS)), which includes all cpp.o and c.o files. Therefore it will run both pattern rules, and output both your lines.

What I think you want to do, is to split $(OBJS) into $(C_OBJS), and $(CPP_OBJS), and then have run1 dependent on one set, and run2 dependent on the other, and then have $(TARGET_EXEC) depend on both.

blackghost
  • 1,730
  • 11
  • 24