ProgDevel
ProgDevel

Reputation: 77

GNU Make: A better way of using both C/C++ targets with different commands

Q: Here is my Makefile fragment below:

SRCS+=$(wildcard *.c *.cpp)
OBJECTS=$(addprefix $(OBJ_DIR)/, $(patsubst %.c,%.o,$(SRCS:.cpp=.o)))
# .....
$(OBJ_DIR)/%.o: %.cpp
    $(CXX) -ggdb -Wall -Wextra -Werror $(INC) $(C_FLAGS) -c -o $@ $<

$(OBJ_DIR)/%.o: %.c
    $(CC) -ggdb -Wall -Wextra -Werror $(INC) $(C_FLAGS) -c -o $@ $<

How can I refactor expression after "OBJECTS" and remove duplication of the similar rules for .cpp and .%c?

Upvotes: 0

Views: 70

Answers (1)

Beta
Beta

Reputation: 99094

OBJECTS := $(patsubst %,$(OBJ_DIR)/%.o,$(basename $(SRCS)))
# Note that you may not need this variable at all.

COMPILE_ARGS = -ggdb -Wall -Wextra -Werror $(INC) $(C_FLAGS) -c -o $@ $<

$(OBJ_DIR)/%.o: %.cpp
    $(CXX) $(COMPILE_ARGS)

$(OBJ_DIR)/%.o: %.c
    $(CC) $(COMPILE_ARGS)

Upvotes: 2

Related Questions