You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写C++ Makefile遇报错:无生成foo.o目标的规则,求协助

解决Makefile中"No rule to make target '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 OBJECTS and main target: These were causing the error because there’s no way to generate those .o files without corresponding .cpp sources. Your test program doesn’t need them anyway.
  • Fixed the -I flag: The original -Itest/catch/catch.hpp was incorrect—-I is for specifying header search directories, not individual files. Using -Itest lets your code correctly find catch/catch.hpp via the #include "catch/catch.hpp" line.
  • Simplified testBuild: Now it directly compiles test/TestCase.cpp, which already includes all your .hpp files. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:45:23