Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make file: compiling all .cpp files to .o files

Tags:

makefile

I'm trying to create a make file which will compile all the .cpp files in the test directory to .o files in the obj directory. Below is an abridged version of what I am doing. The problem is that the calls made to compile to the .o files have the proper .o name, but they all are compiling the same .cpp file.

gcc -c -o obj/foo.o test/foo.c
gcc -c -o obj/bar.o test/foo.c
gcc -c -o obj/baz.o test/foo.c

What do I need to change to make it compile the corresponding .cpp file?

CPP_FILES := $(wildcard test/*.cpp)
OBJ_FILES = $(patsubst test/%.cpp,obj/%.o,$(CPP_FILES))


obj/%.o: $(CPP_FILES)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

executable : $(OBJ_FILES) foo.a
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@

Thanks.

like image 527
Tom Avatar asked Aug 15 '10 20:08

Tom


People also ask

What is CPP O in makefile?

It's a suffix rule telling make how to turn file. cpp into file.o for an arbitrary file . $< is an automatic variable referencing the source file, file. cpp in the case of the suffix rule. $@ is an automatic variable referencing the target file, file.o .

How do I include a CPP file in another file?

You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the . cpp file prior to compilation.

What is $@ in makefile?

The file name of the target of the rule. If the target is an archive member, then ' $@ ' is the name of the archive file. In a pattern rule that has multiple targets (see Introduction to Pattern Rules), ' $@ ' is the name of whichever target caused the rule's recipe to be run.

Can you have multiple cpp files in project?

Visual C++ For creating more code files to go into a project, use the "Add New Item" under the "Project" menu to add new C++ code files. An executable can consist of many files, but can have only one main() function!


1 Answers

You need to match % for your template rule. at the moment you are saying that every .o depends on every cpp file. And $< is the first of them.

Replace it with:

obj/%.o : test/%.cpp
like image 139
Douglas Leeder Avatar answered Oct 23 '22 05:10

Douglas Leeder