Automatically generating a target from the original Make File list

I have this directory structure.

app/
   src
   include
   lib/
       src
   maincode/
           main.cc
           Makefile

I want to create an automatic target from the source list in a makefile. Therefore, I do not need to write a rule for each file.

Example

source=\
        ../src/a.cpp
        ../src/ab.cpp
        ../lib/src/b.cpp

I want to write a rule like

%.o:%.cpp

so I don’t need to repeat the rule for each file. How can i achieve this?

+3
source share
3 answers

Edit: find command must be inside shell variable

If you are using Linux, I think you can use:

SOURCES=$(shell find . -name *.cpp)
OBJECTS=$(SOURCES:%.cpp=%.o)

%.o: %.cpp
    <command to compile>
+7
source

I like Sagar's answer, although it took me a bit to figure out that I wanted an additional rule to cause the creation of objects:

    SOURCES=$(shell find . -name *.cpp)
    OBJECTS=$(SOURCES:%.cpp=%.o)

    all: $(OBJECTS)

    %.o: %.cpp
         <command to compile dependencies $< into target $@ >  $< -o  $@ 
+2
source
CPP        = g++
CPPFLAGS   = -Wall -pedantic -O2 -g -c

SOURCES    := ${wildcard *.cpp}
OBJECTS    := ${SOURCES:.cpp=.o}

.PHONY:    all clean

.SUFFIXES: .cpp .o

all:       main

main:      $(OBJECTS)

.cpp.o:
    $(CPP) $(CPPFLAGS) $< -o $@

clean:
    -rm -fv *.o

.

+2

Source: https://habr.com/ru/post/1796279/


All Articles