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

Makefile中g++自定义Flag未生效问题求助

问题:Makefile自定义编译规则未触发,依赖头文件缺失导致调用内置规则

我在Makefile中定义了MYCPPFLAGS变量,编写了%.o: %.cpp %.h编译规则,但执行make dessiner.o时,make未使用自定义规则,而是调用内置规则,导致g++命令中无MYCPPFLAGS内容,且因缺少-std=c++11出现编译错误。通过make -d和make -r验证发现,因缺少对应.h文件,自定义规则未被触发,求助解决该问题。

Makefile内容

MYCPPFLAGS := what a surprise

%.o: %.cpp %.h
    g++ $(MYCPPFLAGS) -c $< -o $@

dumpy:
    echo $(MYCPPFLAGS)

终端执行结果

grenx08{lc177705}hw-m2-cpp-07-dessiner: make dumpy
echo what a surprise
what a surprise
grenx08{lc177705}hw-m2-cpp-07-dessiner: make dessiner.o
g++    -c -o dessiner.o dessiner.cpp
dessiner.cpp:18:13: warning: override controls (override/final) only available with -std=c++11 or -std=gnu++11 [enabled by default]

[... 一系列因未使用std=c++11选项导致的警告/错误] 

make: *** [dessiner.o] Error 1

环境版本

grenx08{lc177705}hw-m2-cpp-07-dessiner: make -v
GNU Make 3.82
Built for x86_64-redhat-linux-gnu
Copyright (C) 2010  Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
grenx08{lc177705}hw-m2-cpp-07-dessiner: g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

验证信息

grenx08{lc177705}hw-m2-cpp-07-dessiner: make -d dessiner.o
GNU Make 3.82
Built for x86_64-redhat-linux-gnu
[大量输出]
  No need to remake target `dessiner.cpp'.
 Finished prerequisites of target file `dessiner.o'.
Must remake target `dessiner.o'.
Invoking builtin recipe to update target `dessiner.o'.
g++    -c -o dessiner.o dessiner.cpp
[其他无关输出]

grenx08{lc177705}hw-m2-cpp-07-dessiner: make -r dessiner.o
make: *** No rule to make target `dessiner.o'.  Stop.

解决方案

1. 调整规则依赖,适配有无头文件的场景

自定义规则要求%.o必须依赖%.cpp和%.h,如果dessiner.h不存在,这条规则就不生效,make会 fallback 到内置规则。可以拆分规则,同时覆盖两种情况:

MYCPPFLAGS := -std=c++11 what a surprise

# 针对有同名头文件的源文件
%.o: %.cpp %.h
    g++ $(MYCPPFLAGS) -c $< -o $@

# 针对无同名头文件的源文件
%.o: %.cpp
    g++ $(MYCPPFLAGS) -c $< -o $@

dumpy:
    echo $(MYCPPFLAGS)

2. 利用Make预定义变量覆盖内置规则

GNU Make的内置.cpp.o规则会自动使用CXXFLAGS(C++编译选项)和CPPFLAGS(预处理选项),直接定义这些变量无需写自定义规则,更简洁:

CXXFLAGS := -std=c++11 what a surprise

# 无需自定义%.o规则,内置规则会自动应用CXXFLAGS
dumpy:
    echo $(CXXFLAGS)

3. 禁用内置规则并指定明确目标(不推荐)

用-r参数禁用所有内置规则,但需要为每个目标写明确的编译规则,适合小项目:

MYCPPFLAGS := -std=c++11 what a surprise

dessiner.o: dessiner.cpp
    g++ $(MYCPPFLAGS) -c $< -o $@

dumpy:
    echo $(MYCPPFLAGS)

执行时需加-r:make -r dessiner.o


内容的提问来源于stack exchange,提问作者Lorenzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:12:33