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.
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 .
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.
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With