GCC optimization/ko

This guide provides an introduction to optimizing compiled code using safe, sane CFLAGS and CXXFLAGS. It also as describes the theory behind optimizing in general.

CFLAGS와 CXXFLAGS란 뭔가요?
CFLAGS and CXXFLAGS are environment variables that are used to tell the GNU Compiler Collection (GCC) what kinds of switches to use when compiling source code. The CFLAGS variable is used for compiling code written in C, while the CXXFLAGS variable is for code written in C++.

이 변수는 프로그램에 대한 많은 양의 디버그 메시지를 줄여주거나 오류 경고 수준을 높이고, 물론 생산 코드의 최적화 수준을 조절하는데 사용할 수도 있습니다. GCC 설명서 에서는 이들 변수에서 사용할 수 있는 옵션과 목적에 대한 완전한 목록을 제공합니다.

어떻게 사용하나요?
CFLAGS and CXXFLAGS can be used in two ways. First, they can be used per-program with Makefiles generated by the program.

However, this should not be done when installing packages found in the Portage tree. Instead, for Gentoo-based machines, set the CFLAGS and CXXFLAGS variables in This way all packages will be compiled using the options specified in

As seen in the example above the CXXFLAGS variable is set to use all the options present in CFLAGS. Most every system should be configured in this manner; additional options for CXXFLAGS are extremely rare in common use cases.

오해
While CFLAGS and CXXFLAGS can be very effective means of getting source code to produce smaller and/or faster binaries, they can also impair the function of the code, bloat its size, slow down its execution time. Setting them incorrectly can even cause compilation failures!

CFLAGS are not a magic bullet; they will not automatically make the system run faster or reduce the size of binaries on the disk. Adding too many flags in an attempt to optimize (or "rice") the system is a sure recipe for failure. The point of diminishing returns is reached rather quickly when dealing with CFLAGS.

Despite the boasts and brags found on the internet, aggressive CFLAGS and CXXFLAGS are far more likely to harm binaries than to do any good. Keep in mind the flags are designed to be used at specific places for specific purposes. Few flags work as intended globally.

준비됐죠?
Being aware of the risks involved, take a look at some sane, safe optimizations. These will hold in good stead and will be endearing to developers the next time a problem is reported on Bugzilla. (Developers will usually request the user to recompile a package with minimal CFLAGS to see if the problem persists. Remember: aggressive flags can ruin code!)

기본
The goal behind CFLAGS and CXXFLAGS is to create code tailor-made to your system; it should function perfectly while being lean and fast, if possible. Sometimes these conditions are mutually exclusive, so this guide will stick to combinations known to work well. Ideally, they are the best available for any CPU architecture. For informational purposes, aggressive flag use will be covered later. Not every option listed on the GCC manual (there are hundreds) will be discussed, but basic, most common flags will be reviewed.

-march
The first and most important option is. This tells the compiler what code it should produce for the system's processor architecture (or arch); it tells GCC that it should produce code for a certain kind of CPU. Different CPUs have different capabilities, support different instruction sets, and have different ways of executing code. The  flag will instruct the compiler to produce specific code for the system's CPU, with all its capabilities, features, instruction sets, quirks, and so on.

의 CHOST 변수에 일반적으로 아키텍처에서 사용하는 플래그를 지정하지만,  플래그는 지정 시스템 프로세서에 맞게 프로그램을 최적화하는데 사용할 수 있습니다. (다른 CPU 중에서) x86과 x86-64 CPU는  플래그를 사용해야 합니다.

어떤 CPU를 가지고 있나요? 찾아보려면 다음 명령을 실행하십시오:

와  값에 대한 자세한 내용을 살펴보려면 다음 명령을 사용하십시오:

이제  동작을 보겠습니다. 예제는 옛날 펜티엄 III 칩입니다:

64-bit AMD CPU에 대한 또 다른 설정 내용입니다:

어떤 CPU를 쓰는지 모르겠거나 어떤 설정을 선택해야 할지 모르겠다면, 아마 그냥 설정을 사용할 수 있습니다. 이 플래그를 사용하면 GCC는 프로세서를 감지하고 자동으로 적당한 플래그를 설정합니다. 그러나 다른 CPU에서 사용할 패키지를 컴파일하려 한다면 이 플래그를 쓰면 안됩니다.

하나의 컴퓨터에서 패키지를 컴파일 하는데 다른 컴퓨터에서 실행하려 한다면(예를 들어 더 느리고 오래된 머신에서 실행할 바이너리를 빌드하는데 더 빠른 컴퓨터를 사용하는 경우), 를 사용하지 마십시오. "Native"는 말 그대로 해당 CPU에서만 동작할 코드를 만듦을 의미합니다. AMD Athlon 64 CPU에서  플래그로 빌드한 프로그램은 옛날 VIA C3 CPU에서 실행할 수 없습니다.

또한 이 말고도 와   플래그가 있습니다. 이 플래그는 보통  옵션을 쓰지 못할때만 사용합니다. 어떤 프로세서 아키텍처에서는 아니면  가 필요합니다. 불행하게도 GCC의 동작은 어떤 한 아키텍처에서 다음 아키텍처로 각각의 플래그를 부여하는데 있어 일관성이 꽤 있는 것이 아닙니다.

x86과 x86-64 CPU에서  플래그를 통해 존재하는 모든 명령 셋과 올바른 ABI를 활용하여 CPU에 대한 지정 코드를 생성합니다. 이전의 다른 CPU에 대한 이전 호환성은 없습니다. i386과 i486 같은 예전 CPU에 대해 코드를 생성할 때만 의 사용을 고려하는것이 좋습니다. 플래그는 보다 훨씬 일반적인 코드를 만들어냅니다. 각각의 CPU에 대한 적당한 코드를 만들어내겠지만서도, 존재하는 명령셋과 ABI에 맞춰주진 못합니다. x86이나 x86-64 시스템에서  플래그는 오래된 요소이므로 사용하지 마십시오.

비 x86/x86-64 CPU에서는(Sparc, 알파 PowerPC)  대신   또는  가 필요할듯 합니다. 이 아키텍처에서는  /   옵션이 (x86/x86-64의)   처럼 동작하기도 합니다...만 플래그 이름은 달라집니다. 다시 말해, GCC의 동작과 플래그 이름은 전 아키텍처에 대해 일관성이 있는건 아니므로, 시스템에서 사용할 아키텍처가 무엇인지 정하려면 GCC 설명서를 확인하십시오.

-O
Next up is the  variable. This variable controls the overall level of optimization. Changing this value will make the code compilation take more time and will use much more memory, especially as the level of optimization is increased.

There are seven  settings: ,  ,  ,  ,  ,  , and. Only use one of them in

는 예외로 간주하고, 각각의  설정은 몇가지 추가 플래그를 활성화 하므로, GCC 메뉴얼의 최적화 옵션 장을 읽어 각각의   레벨에서 어떤 플래그를 활성화 하는지, 이들이 각각 어떤 동작을 취하는지 알아보십시오.

Let us examine each optimization level:


 * : This level (that is the letter "O" followed by a zero) turns off optimization entirely and is the default if no  level is specified in CFLAGS or CXXFLAGS . This reduces compilation time and can improve debugging info, but some applications will not work properly without optimization enabled. This option is not recommended except for debugging purposes.


 * : the most basic optimization level. The compiler will try to produce faster, smaller code without taking much compilation time. It is basic, but it should get the job done all the time.


 * : A step up from . The recommended level of optimization unless the system has special needs.   will activate a few more flags in addition to the ones activated by  . With , the compiler will attempt to increase code performance without compromising on size, and without taking too much compilation time.


 * : the highest level of optimization possible. It enables optimizations that are expensive in terms of compile time and memory usage. Compiling with   is not a guaranteed way to improve performance, and in fact, in many cases, can slow down a system due to larger binaries and increased memory usage.   is also known to break several packages. Using   is not recommended.


 * : optimizes code for size. It activates all  options that do not increase the size of the generated code. It can be useful for machines that have extremely limited disk storage space and/or CPUs with small cache sizes.


 * : GCC4.8에 새로운 일반 최적화 레벨 를 도입했습니다. 빠른 컴파일을 필요로 하며 실행시간 성능의 타당한 수준을 제공하면서 우수한 디버깅 경험을 할 수 있게 바로 잡았습니다. 개발에 있어 전체적인 경험은 기본 최적화 레벨  보단 낫습니다. 참고로  는  를 의미하지 않으며, 디버깅에 혼란을 주는 최적화 기능을 끌 뿐입니다.


 * : GCC 4.7에서 새로 도입했으며,,   ,  , and  로 이루어져 있습니다. 이 옵션은 엄격한 표준 준수를 깨며, 사용을 권장하지 않습니다.

As previously mentioned,  is the recommended optimization level. If package compilation fails and while not using, try rebuilding with that option. As a fallback option, try setting the CFLAGS and CXXFLAGS to a lower optimization level, such as  or even   (for error reporting and checking for possible problems).

-pipe
A common flag is. This flag has no effect on the generated code, but it makes the compilation process faster. It tells the compiler to use pipes instead of temporary files during the different stages of compilation, which uses more memory. On systems with low memory, GCC might get killed. In those cases do not use this flag.

-fomit-frame-pointer
This is a very common flag designed to reduce generated code size. It is turned on at all levels of  (except  ) on architectures where doing so does not interfere with debugging (such as x86-64), but it may need to activated. In that case add it to the flags. Though the GCC manual does not specify all architectures, it is turned on by using the  option. It's still necessary to explicitly enable the  option, to activate it on x86-32 with GCC up to version 4.6, or when using   on x86-32 with any version of GCC. However, using  will make debugging hard or impossible.

In particular, it makes troubleshooting applications written in Java much harder, though Java is not the only code affected by using this flag. So while the flag can help, it also makes debugging harder; backtraces in particular will be useless. When not doing software debugging and no other debugging-related CFLAGS such as  have been used, then try using.

-msse, -msse2, -msse3, -mmmx, -m3dnow
These flags enable the Streaming SIMD Extentions (SSE), SSE2, SSE3, MMX, and 3DNow! instruction sets for x86 and x86-64 architectures. These are useful primarily in multimedia, gaming, and other floating point-intensive computing tasks, though they also contain several other mathematical enhancements. These instruction sets are found in more modern CPUs.

Normally none of these flags need to be added to, as long as the system is using the correct  (for example,   implies  ). Some notable exceptions are newer VIA and AMD64 CPUs that support instructions not implied by  (such as SSE3). For CPUs like these additional flags will need to be enabled where appropriate after checking.

근데 -funroll-loops -fomg-optimize로 성능이 더 좋아졌는데요?!
No, you only think you do because someone has convinced you that more flags are better. Aggressive flags will only hurt applications when used system-wide. Even the GCC manual says that using  and   will make code larger and run more slowly. Yet for some reason, these two flags, along with,  ,  , and similar flags, continue to be very popular among ricers who want the biggest bragging rights.

사실은 이런 플래그 추가 사용이 굉장히 무모한 행위라는 점입니다. 어떤 플래그가 무슨 역할을 하는지에 대해서는 바람직한 젠투 포럼en 과 버그질라en 에서 확인해보십시오. 좋을게 하나도 없습니다!

You do not need to use those flags globally in CFLAGS or CXXFLAGS. They will only hurt performance. They may make you sound like you have a high-performance system running on the bleeding edge, but they don't do anything but bloat the code and get your bugs marked INVALID or WONTFIX.

이런 위험한 플래그는 필요하지 않습니다. 사용하지 마십시오. 기본 플래그,  ,  에 집착하십시오.

3 보다 높은 -O 레벨은 어떤가요?
Some users boast about even better performance obtained by using,  , and so on, but the reality is that   levels higher than 3 have no effect. The compiler may accept CFLAGS like, but it actually doesn't do anything with them. It only performs the optimizations for, nothing more.

증명이 좀 더 필요한가요? 소스 코드를 시험해보십시오:

보시는 바와 같이 3보다 큰 값은  처럼 취급합니다.

대상 머신이 아닌곳에서 컴파일은 어떤가요?
Some readers might wonder if compiling outside the target machine with a strictly inferior CPU or GCC sub-architecture will result in inferior optimization results (compared to a native compilation). The answer is simple: No. Regardless of the actual hardware on which the compilation takes place and the CHOST for which GCC was built, as long as the same arguments are used (except for ) and the same version of GCC is used (although minor version might be different), the resulting optimizations are strictly the same.

To exemplify, if Gentoo is installed on a machine whose GCC's CHOST is i686-pc-linux-gnu, and a Distcc server is setup on another computer whose GCC's CHOST is i486-linux-gnu, then there is no need to be afraid that the results would be less optimal because of the strictly inferior sub-architecture of the remote compiler and/or hardware. The result would be as optimized as a native build, as long as the same options are passed to both compilers (and the  parameter doesn't get a   argument). In this particular case the target architecture needs to be specified explicitly as explained in Distcc and -march=native.

The only difference in behavior between two GCC versions built targeting different sub-architectures is the implicit default argument for the  parameter, which is derived from the GCC's CHOST when not explicitly provided in the command line.

중복 플래그는 무엇인가요?
Oftentimes CFLAGS and CXXFLAGS that are turned on at various  levels are specified redundantly in. Sometimes this is done out of ignorance, but it is also done to avoid flag filtering or flag replacing.

Flag filtering/replacing is done in many of the ebuilds in the Portage tree. It is usually done because packages fail to compile at certain  levels, or when the source code is too sensitive for any additional flags to be used. The ebuild will either filter out some or all CFLAGS and CXXFLAGS, or it may replace  with a different level.

The Gentoo Developer Manual outlines where and how flag filtering/replacing works.

It's possible to circumvent  filtering by redundantly listing the flags for a certain level, such as , by doing things like:

However, this is not a smart thing to do. CFLAGS are filtered for a reason! When flags are filtered, it means that it is unsafe to build a package with those flags. Clearly, it is not safe to compile your whole system with  if some of the flags turned on by that level will cause problems with certain packages. Therefore, you shouldn't try to "outsmart" the developers who maintain those packages. Trust the developers. Flag filtering and replacing is done for your benefit! If an ebuild specifies alternative flags, then don't try to get around it.

허용할 수 없는 플래그로 꾸러미를 빌드하면, 문제로 거의 직면하게 됩니다. 버그질라에 이 문제를 보고할 때, 에 사용하는 플래그가 분명히 나타나며, 누군가가 해당 플래그를 빼고 다시 컴파일하라고 알려줄겁니다. 처음에 언급한대로 중복 플래그를 빼서 다시 컴파일하는일이 없도록 하십시오! 개발자들보다 여러분이 더 잘 알거라고 멋대로 판단하지 마십시오.

LDFLAGS란 무엇인가요?
The Gentoo developers have already set basic, safe LDFLAGS in the base profiles, so they do not need to be changed.

패키지별로 플래그를 사용해도 되나요?
Information on how to use per-package environment variables (including CFLAGS ) is described in the Gentoo Handbook, "Per-Package Environment Variables".

자료
다음 자료는 최적화에 대해 더 이해하는데 도움이 될 것입니다:


 * GCC 온라인 문서


 * 젠투 설치 핸드북 5장


 * man make.conf


 * 위키피디아


 * 젠투 포럼