Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cpp files from different directories compiled into one folder?

I have a number of C++ files distributed in several folders.

a_library/
    file1.cpp
    file2.cpp
    category1/
        file3.cpp
        file4.cpp

They are guaruanteed to be uniquely named. I want to compile all those C++ files to seperate Object-files in the obj/ directory.

I have a list of all source-files with relative path, and their corresponding destination-names.

a_library/file1.cpp
a_library/file2.cpp
a_library/category1/file3.cpp
a_library/category1/file4.cpp

obj/file1.obj
obj/file2.obj
obj/file3.obj
obj/file4.obj

How can I make a rule that will convert a C++ file from the first list to a object-file from the second one?

These attempts do not work:

obj/%.obj: %:cpp
    # ...

%.obj: %.cpp
    # ...

.cpp.obj:
    # ...

I would like to not write rules like this:

obj/%.obj: a_library/%.cpp
    # ...

obj/%.obj: a_library/category1/%.cpp
    # ...
like image 861
Niklas R Avatar asked Jul 26 '12 10:07

Niklas R


1 Answers

Try setting VPATH:

VPATH = a_library:a_library/category1
obj/%.o: %.cpp
    $(CXX) -c $(CPPFLAGS) $(CFLAGS) $(CXXFLAGS) -o $@ $<

And to add complete file list (I would recommend you explicitely list the files, do not use $(wildcard ...) function) and linking of the application:

files := main.cpp $(wildcard a_library/*.cpp) a_library/category1/file.cpp

obj/application: $(patsubst %.cpp,obj/%.o,$(notdir $(files)))
    $(CXX) $(CFLAGS) $(CXXFLAGS) $(LDFLAGS) -o $@ $+

The $(wildcard) has an annoying tendency to pick up anything in the directories, like one-off test files or temporaries (if they happen to have a fitting name: ~file.cpp).

like image 86
fork0 Avatar answered Oct 19 '22 05:10

fork0