Linux 使用 makefile 时如何禁用 GCC 优化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9262456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:33:40  来源:igfitidea点击:

How do I disable GCC optimization when using makefiles?

c++linuxoptimizationgccmakefile

提问by inline

I've just started learning Linux and I'm having some trouble disabling GCC's optimization for one of my C++ projects.

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

The project is built with makefiles like so...

该项目是用像这样的makefile构建的......

make -j 10 && make install

I've read on various sites that the command to disable optimization is something along the lines of...

我在各种网站上都读到过,禁用优化的命令类似于...

gcc -O0 <your code files>

Could someone please help me apply this to makefiles instead of individual code? I've been searching for hours and have come up empty handed.

有人可以帮我把它应用到makefile而不是单个代码吗?我一直在寻找几个小时,却空手而归。

采纳答案by sehe

In some standard makefile settings you could

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

make -j10 -e CPPFLAGS=-O0

But the makefile might use other substitution variables or override the environment. You need to show us the Makefile in order to propose edits

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

回答by rasmus

For example, an optimized compilations can be written as:

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

all:
    g++ -O3 main.cpp

A compilation with debug information (no optimization) can be written as:

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

all:
    g++ -g main.cpp

回答by Martin York

The simplest (useful) makefile that allows debug/release mode is:

允许调试/发布模式的最简单(有用)的 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)

Usage Default build (No specified optimizations)

用法默认构建(未指定优化)

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

Usage: Release build (uses -O3)

用法:发布构建(使用 -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

Usage: Debug build (uses -g)

用法:调试构建(使用 -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