3

I have this directory structure.

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

I want to generate automatic target from the source list in makefile. So I don't have to write rule for each file.

Example

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

I want to write rule like

%.o:%.cpp

so that I don't have to repeat rule for each file. How I can achieve this ?

3 Answers 3

7

Edit: the find command should be inside a 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>
2
  • I am using this type SOURCEFILE= \ $(SRC_DIR)/vinit.cc \ $(SRC_DIR)/vout.cc \ OBJECTS=$(SOURCEFILE:%.cc=%.o) but it is not working fine
    – Vivek Goel
    Mar 4, 2011 at 14:48
  • I am not getting any error . but target is not getting called %.o: %.cc @echo "here" it is not getting called
    – Vivek Goel
    Mar 4, 2011 at 17:19
2

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

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

    all: $(OBJECTS)

    %.o: %.cpp
         <command to compile dependencies $< into target $@ >  $< -o  $@ 
2
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

For more info see the man

1
  • 2
    Convention says all instances of CPP here should be replaced with CXX. This is because CPP in a makefile actually usually means C PreProcessor, not C++. CXX is taken to mean C++. The flags shown here in CPPFLAGS are not for the preprocessor but for the compiler itself. Of course, it doesn't actually matter what you call your variables - you could call them BERT and ERNIE - but conventions are only useful if people follow them! Sep 15, 2015 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.