编写C++ Makefile遇报错:无生成foo.o目标的规则,求协助
Hey, let's break down why your Makefile is throwing that frustrating error and fix it up.
问题根源
Your Makefile defines OBJECTS = foo.o bar.o baz.o and sets main as dependent on those object files. But here's the catch: Make’s default rules expect to find corresponding foo.cpp, bar.cpp, and baz.cpp files to compile into those .o targets. Since you only have .hpp files (with all your class implementations inside them) and no matching .cpp sources, Make has no idea how to create those .o files—hence the error.
From your setup, it looks like you only need to compile and run TestCase.cpp to test your classes, so those separate .o files and the main target are totally unnecessary here.
修正后的Makefile
Here’s a streamlined version of your Makefile that works with your current file structure:
CXX = g++ CXXFLAGS = -std=c++11 -Wall testBuild: $(CXX) $(CXXFLAGS) -Itest -o test/TestCase test/TestCase.cpp test: clean testBuild test/TestCase --success clean: $(RM) *.o *.gch test/TestCase
关键改动说明
- Removed
OBJECTSandmaintarget: These were causing the error because there’s no way to generate those.ofiles without corresponding.cppsources. Your test program doesn’t need them anyway. - Fixed the
-Iflag: The original-Itest/catch/catch.hppwas incorrect—-Iis for specifying header search directories, not individual files. Using-Itestlets your code correctly findcatch/catch.hppvia the#include "catch/catch.hpp"line. - Simplified
testBuild: Now it directly compilestest/TestCase.cpp, which already includes all your.hppfiles. This is all you need to build your test executable.
额外注意事项
If your .hpp files ever contain non-inline, non-template code (which is generally not recommended—best practice is to separate declarations in .hpp and implementations in .cpp), you’ll need to create matching .cpp files for each class. For example, foo.cpp would include #include "foo.hpp" and contain the non-inline implementations, allowing Make to generate foo.o using its default rules. But for your current setup with all code in headers, the adjusted Makefile above works perfectly.
内容的提问来源于stack exchange,提问作者Phillip Burt

