如何在使用makefiles时禁用GCC优化

How do I disable GCC optimization when using makefiles?

本文关键字:GCC 优化 makefiles      更新时间:2023-10-16

我刚开始学习Linux,在为我的一个C++项目禁用GCC的优化时遇到了一些问题。

该项目是用这样的makefile构建的…

make -j 10 && make install

我在各种网站上读到,禁用优化的命令是沿着。。。

gcc -O0 <your code files>

有人能帮我把它应用到makefile而不是单个代码中吗?我找了好几个小时都没找到。

在一些标准的makefile设置中,您可以

make -j10 -e CPPFLAGS=-O0

但是makefile可能会使用其他替换变量或覆盖环境。您需要向我们展示Makefile,以便建议编辑

允许调试/发布模式的最简单(有用)的makefile是:

#
# Define the source and object files for the executable
SRC     = $(wildcard *.cpp)
OBJ     = $(patsubst %.cpp,%.o, $(SRC))
#
# set up extra flags for explicitly setting mode
debug:      CXXFLAGS    += -g
release:    CXXFLAGS    += -O3
#
# Link all the objects into an executable.
all:    $(OBJ)
    $(CXX) -o example $(LDFLAGS) $(OBJ) $(LOADLIBES) $(LDLIBS)
#
# Though both modes just do a normal build.
debug:      all
release:    all
clean:
    rm $(OBJ)

用法默认构建(没有指定的优化)

> make
g++    -c -o p1.o p1.cpp
g++    -c -o p2.o p2.cpp
g++ -o example p1.o p2.o

用法:发布版本(使用-O3)

> make clean release
rm p1.o p2.o
g++ -O3   -c -o p1.o p1.cpp
g++ -O3   -c -o p2.o p2.cpp
g++ -o example p1.o p2.o

用法:调试构建(使用-g)

> make clean debug
rm p1.o p2.o
g++ -g   -c -o p1.o p1.cpp
g++ -g   -c -o p2.o p2.cpp
g++ -o example p1.o p2.o

例如,优化编译可以写成:

all:
    g++ -O3 main.cpp

带有调试信息(无优化)的编译可以写成:

all:
    g++ -g main.cpp