I have some source .cpp files in the same directory, and I want to compile them as object file.
Some of them needs “extra” libraries (same libs for all files) to be linked with and some of them don’t, I’d like to write general rules to match the right files, without writing specific rule for each file with extra flags.
More in detail I want to refactor my Makefile so that I don’t have to specify different rules for the source files SourceFileOpenCVNeeded.cpp OCVAlsoHere.cpp TheSameForMe.cpp (now they’re few, but they could be many more).
Here is what my makefile actually looks like:
CPP_FILES := $(wildcard src/*.cpp)
OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.o)))
MAIN_SRC := main.cpp
OCV_LIBS := `pkg-config opencv --libs`
OCV_PATH := `pkg-config opencv --cflags`
MY_LIB := launcher
LD_FLAGS := $(MAIN_SRC) -L. -l$(MY_LIB) $(OCV_LIBS)
CC_FLAGS := -c -fPIC
AR_FLAGS := rcs
STATIC_LIB := lib$(MY_LIB).a
CC := g++
EXEC := test
all: lib main
main:
$(CC) $(LD_FLAGS) -o $(EXEC)
lib: $(OBJ_FILES)
ar $(AR_FLAGS) $(STATIC_LIB) $^
obj/SourceFileOpenCVNeeded.o: src/SourceFileOpenCVNeeded.cpp
$(CC) $(OCV_PATH) $(CC_FLAGS) $(OCV_LIBS) -c -o $@ $<
obj/OCVAlsoHere.o: src/OCVAlsoHere.cpp
$(CC) $(OCV_PATH) $(CC_FLAGS) $(OCV_LIBS) -c -o $@ $<
obj/TheSameForMe.o: src/TheSameForMe.cpp
$(CC) $(OCV_PATH) $(CC_FLAGS) $(OCV_LIBS) -c -o $@ $<
obj/%.o: src/%.cpp
$(CC) $(CC_FLAGS) -c -o $@ $<
clean:
rm -f $(OBJ_FILES) $(STATIC_LIB) $(EXEC)
PS: any other improvements that can be added to my Makefile?
You might be able to use target-specific variables, e.g. (not tested)