1
2# OpenHarmony Compilation Specifications
3
4## Overview
5
6**Introduction**
7
8This topic covers C, C++, and Java compiler options or system configurations, including language options, warning options, security options, general options, code generation options, architecture options, optimization options, and compiler macros.
9
10**Scope**
11
12This topic specifies the C, C++, and Java compiler options or system configurations to be added during the compilation and build, and briefly describes the functionalities of these options. It also explains the involved exceptions.
13
14This topic does not cover security options in non-OS cases (such as bare core, BIOS, Bootloader, and BSBC). It is recommended that stack protection be implemented before related specifications are released.
15
16You can apply for arbitration for any dispute over exceptions that are not described in this document.
17
18**Clause Composition**
19
20Each clause generally includes the title, level, and description. In the description part, "Positive Example" provides an example that meets the clause, and "Negative Example" provides an example that does not meet the clause.
21
22**Title**
23
24Brief description of the clause.
25
26Clauses are classified into principles and guidelines. Principles can be used to evaluate the quality of guidelines and serve as a guide for their adjustment. Guidelines are practices that need to be followed or referenced. The identifier preceding a title tells whether the clause is a principle (P) or guideline (G).
27
28As stipulated in *Security Engineering Guidelines*, a principle identifier takes the format of P.Number, and a guideline identifier takes the format of G.Language.Element.Number, where **Language** indicates the programming language in use, **Element** is an abbreviation of the key element (corresponding to the level-1 title in this topic) in the domain, and **Number** is a 2-bit number incremented from 01.
29
30| Language | Element | Catalog    | Language | Element | Catalog        |
31|----------|---------|----------|----------|---------|--------------|
32| C&C++    | LANG    | Language options| C&C++    | WARN    | Warning options    |
33| C&C++    | SEC     | Security options| C&C++    | CDG     | Code generation options|
34| C&C++    | OPT     | Optimization options| C&C++    | MD      | Architecture options    |
35| C&C++    | OVA     | General options| C&C++    | LNK     | Link options    |
36| C&C++    | DBG     | Debugging options| C&C++    | PRE     | Compiler macros      |
37| C&C++    | OTH     | Other    | Java      | JAVAC     | Javac   |
38| Java    | MAVEN   | Maven   |   |    |        |
39
40**Level**
41
42Guidelines are classified into requirements and recommendations by level.
43
44-   Requirement: a guideline that must be followed in principle, but can be implemented phase by phase based on the specific product version plan.
45
46-   Recommendation: a best practice that helps mitigate risks. Your team can determine whether to follow the recommendation based on actual business conditions.
47
48**Description**
49
50This part describes the clause, its working principle, and positive and negative examples. For some clauses, exceptions are provided.
51
52##  C/C++ Compiler Options
53
54### Language Options
55
56##### G.C&C++.LANG.01 Explicitly set the compiler language standards.
57
58**[Type]** Requirement
59
60**[Description]** According to the time sequence, common ISO C standards include **-std=c90**, **-std=c99**, and **-std=c11**, and the corresponding GNU extension standards are **-std=gnu90**, **-std=gnu99**, and **-std=gnu11**.
61
62According to the time sequence, common ISO C++ standards include **-std=c++98**, **-std=c++11**, **-std=c++14**, and **-std=c++1z**, and the corresponding GNU extension standards are **-std=gnu++98**, **-std=gnu++11**, **-std=gnu++14**, and **-std=gnu++1z**.
63
64**-ansi** corresponds to **-std=c90** in the ISO C standard and **-std=c++98** in the ISO C++ standard.
65
66The GNU extensions fully support the corresponding ISO standards.
67
68Options such as **-Wpedantic**, **-pedantic**, and **-pedantic-errors** are used to check whether the ISO standards are strictly complied with. If the syntax does not comply with the ISO standards, a warning is generated. The GNU extension syntax may also trigger warnings.
69
70##### G.C&C++.LANG.02 Use the new language standards.
71
72**[Type]** Recommendation
73
74##### G.C&C++.LANG.03 Explicitly set the char type, either **-fsigned-char** or **-funsigned-char**.
75
76**[Type]** Recommendation
77
78**[Description]** In the x86 environment, char is of the signed type by default. In the ARM64 environment, char is of the unsigned type by default. Generally, use the **-fsigned-char** option to ensure that the compiler can adapt to instruction sets of different platforms.
79
80If char is equivalent to unsigned char (this is the case for some products), you are advised to use the **-funsigned-char** option.
81
82##### G.C&C++.LANG.04 DO NOT enable -fpermissive for C++.
83
84**[Type]** Requirement
85
86**[Description]** The **-fpermissive** option downgrades syntax errors in the C++ code to warnings. Therefore, do not enable this option.
87
88### Warning Options
89
90#### Options
91
92##### G.C&C++.WARN.01 Enable -Wall to check for useful warnings.
93
94**[Type]** Requirement
95
96**[Description]** **-Wall** is a set of useful warning options recognized by the GNU Compiler Collection (GCC), including **-Wpointer-sign**, **-Wframe-address**, **-Wmaybe-uninitialized**, and **-Wint-in-bool-context**. Learn the meanings of these warnings and modify code to clear them.
97
98##### G.C&C++.WARN.02 Enable -Wextra to check for additional warnings except -Wall. Use -Wno-XXXX to suppress huge numbers of false positives.
99
100**[Type]** Requirement
101
102**[Description]** **-Wextra** is a set of useful warning options except **-Wall**, including **-Wempty-body**, **Wmissing-field-initializers**, and **-Wunused-parameter**.
103
104Enabling **-Wextra** may cause many false positives. Based on the actual test, you can use **-Wno-XXXX** to suppress false positives. For example, if your product has a huge number of false positives for **-Wunused-parameter\-Wmissing-field-initializers**, you can set **-Wextra -Wno-unused-parameter\-Wno-missing-field-initializers**, after being approved by the chief software engineer of the product line.
105
106##### G.C&C++.WARN.03 Enable -Weffc++ to check for Scott Meyers' Effective C++ options.
107
108**[Type]** Recommendation
109
110**[Description]** **-Weffc++** is a set of warning options corresponding to Scott Meyers' Effective C++ options.
111
112#### Warning Suppression
113
114##### G.C&C++.WARN.04 DO NOT enable -w to suppress all warnings.
115
116**[Type]** Requirement
117
118**[Description]** The warnings displayed by the compiler are useful for identifying poor code and obscure bugs. Enabling the **-w** option will suppress all warnings.
119
120##### G.C&C++.WARN.05 DO NOT enable -Wno-XXXX to suppress all warning options contained in -Wall.
121
122**[Type]** Requirement
123
124**[Description]** **-Wall** is a set of useful alarm options recognized by the GCC compiler. Do not use **-Wno-pointer-sign**, **-Wno-frame-address**, **-Wno-maybe-uninitialized**, or **-Wno-int-in-bool-context** to suppress the **-Wpointer-sign**, **-Wframe-address**, **-Wmaybe-uninitialized**, and **-Wint-in-bool-context** options contained in **-Wall**.
125
126##### G.C&C++.WARN.06 DO NOT enable -Wno-error= XXXX to degrade a specific warning that has been upgraded to an error to a warning again.
127
128**[Type]** Requirement
129
130**[Description]** **-Werror=XXXX** escalates a warning to an error. **-Wno-error= XXXX** downgrades a warning that has been escalated to an error to a warning again.
131
132##### G.C&C++.WARN.07 DO NOT enable -Wno-XXXX to suppress the warning options enabled by the compiler by default.
133
134**[Type]** Recommendation
135
136**[Description]** The warning options enabled by the compiler by default are useful options recognized by the GCC, such as **-Wwrite-strings**, **-Wdelete-incomplete**, and **-Wsizeof-array-argument**. Learn the meanings of these warnings and modify code to clear them.
137
138**[Negative Example]** In the build project of a component, **-Wno-write-strings** is used to suppress the **-Wwrite-strings** warning for 7749 times.
139
140**[Exception]** To ensure build consistency, you can redefine the **\_*****FILE*****\_** macro to eliminate absolute paths. In this case, you can use **-Wno-builtin-macro-redefined** to suppress the **-Wbuiltin-macro-redefined** warning.
141
142#### Warning Escalation
143
144##### G.C&C++.WARN.08 Enable -Werror or -Werror=XXXX to escalate warnings to errors.
145
146**[Type]** Recommendation
147
148**[Description]** Enable the **-Werror** or **-Werror=XXXX** option to escalate warnings to errors.
149
150If **-Werror** is enabled, all warnings are escalated as errors. Once a warning is generated, the compilation will fail. This helps clear all warnings during development.
151
152If **-Werror=XXXX** is enabled, a specific type of warning is escalated as errors. This helps clear the specified warnings during development. Example: **-Werror=implicit-function-declaration** and **-Werror=format-SEC**.
153
154#### Warning Management
155
156##### G.C&C++.WARN.09 Use unified warning options in a build project.
157
158**[Type]** Requirement
159
160**[Description]** Use unified compilation warning options to ensure the same code quality of each part.
161
162#### Functions
163
164##### G.C&C++.WARN.10 Enable -Wtrampolines to check for trampolines pointed to by nested functions.
165
166**[Type]** Recommendation
167
168**[Description]** With the **-Wtrampolines** option enabled, a warning is generated when a nested function points to a trampoline. A trampoline is a small piece of data or code that is created at runtime and resides on the stack. It contains the address of a nested function and is used to indirectly call the nested function. On some platforms, a trampoline consists of only specially processed data. However, on most platforms, it is made up of code and requires an executable stack. For an executable stack, the CPU reads instructions from the stack and executes the instructions. This makes it possible for attackers to run their code in the stack memory by means of buffer overflow attacks.
169
170**[Negative Example]** Define a nested function **fun** in the **main** function, and use the function pointer to call **fun**.
171
172-  Source program
173```
174\#include \<stdio.h\>
175int main(){
176    int ret;
177    int (\*pfunc)(int a, int b);
178    int fun(int a, int b){
179      return a + b;
180    }
181    pfunc = fun;
182    ret = pfunc(10, 20);
183    printf("test gcc option -Wtrampolines! ret = %d\\n", ret);
184    return 0;
185}
186```
187
188-  Compiler options
189```
190gcc -Wtrampolines trampolines.c -o out
191```
192
193-  Compilation result
194```
195warning: trampoline generated for nested function 'fun' [-Wtrampolines]
196```
197**[Exception]** The **-Wtrampolines** option is not supported by xt-xcc and Clang compilers.
198
199##### G.C&C++.WARN.11 Enable -Wformat=2 to check input/output format functions.
200
201**[Type]** Recommendation
202
203**[Description]** **-Wformat=2** is a collection of **-Wformat**, **-Wformat-nonliteral**, **-Wformat-SEC**, and **\-Wformat-y2k**.
204
2051. With the **-Wformat** option enabled, a warning is generated when the parameter type or format of a format function is incorrect.
206
2072. With the **-Wformat-nonliteral** option enabled, a warning is generated when the format string is a non-string constant.
208
2093. **-Wformat-SEC** and **-Wformat-y2k**: If your product has encapsulated input and output framework format functions, declare the format attribute in the API to use the compiler check capabilities. For details, see the following:
210[https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html\#Common-Function-Attributes](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes)
211
212##### G.C&C++.WARN.12 Enable -Wstrict-prototypes to check for unspecified parameter types in the function declaration or definition.
213
214**[Type]** Recommendation
215
216**[Description]** When a function is declared or defined, explicitly specify its parameter type. The compiler checks whether the parameter type in the call matches that in the definition.
217
218**[Negative Example]**
219
220-  Source program
221```
222\#include \<stdio.h\>
223int func(param){
224    return param;
225}
226
227```
228-  Compiler options
229```
230gcc -Wstrict-prototypes strict_prototypes.c -o out
231```
232-  Compilation result
233```
234 warning: function declaration isn't a prototype [-Wstrict-prototypes]  int func(param){
235```
236
237Related document: SEI CERT C Coding Standard DCL07-C.Include the appropriate type
238information in function declarators
239
240#### Binary Consistency
241
242##### G.C&C++.WARN.13 Enable -Wdate-time to check for time macros.
243
244**[Type]** Recommendation
245
246**[Description]** Enable the **-Wdate-time** option to check for **__DATE__**, **TIME**, or **TIMESTAMP** in the code. This ensures binary consistency.
247
248**[Negative Example]**
249
250-  Source program
251```
252\#include \<stdio.h\>
253int main() {
254    printf ("%s %s %s\\n",_DATE_,_TIME_,_TIMESTAMP_);
255    return 0;
256}
257```
258-  Compiler options
259```
260gcc -Wdate-time datetime.c -o out
261```
262-  Compilation result
263```
264warning:macro "_DATE_" might prevent reproducible builds [-Wdate-time] warning:macro "_TIME_" might prevent reproducible builds [-Wdate-time] warning:macro "_TIMESTAMP_" might prevent reproducible builds [-Wdate-time]
265```
266
267#### Statements
268
269##### G.C&C++.WARN.14 Enable -Wfloat-equal to check for equality comparison of floating point numbers.
270
271**[Type]** Requirement
272
273**[Description]** Floating point numbers have precision problems and cannot be accurately determined whether they are equal or not. You are advised to check whether the absolute value of the difference between two numbers is less than the acceptable error. You can use the C function **fabs()** to obtain the absolute value of the difference, and then compare the absolute value with the acceptable error. If the absolute value is less than the acceptable error, the two numbers are equal. Otherwise, they are not equal. Note that no warning is generated when the following comparison operators are used to compare floating point numbers: \>, \<, \>=, and \<=.
274
275**[Negative Example]**
276
277-  Source program
278```
279\#include \<stdio.h\>
280int main() {
281    double a = 0.3;
282    double b = 0.6;
283    ouble c = 0.9;
284    if ((a+b) == c) {
285        /\* It seems that a+b is equal to c, but actually not. \*/
286        printf("double equal\\n");
287    }
288    return 0;
289}
290```
291
292-  Compiler options
293```
294gcc -Wfloat-equal float_equal.c -o out
295```
296
297In the preceding example, when double-precision floating point numbers are compared, the compiler generates "warning:comparing floating point with == or != is unsafe[-Wfloat-equal]". The correct method is to set an acceptable error range. If the absolute value of the difference between two floating point numbers is within the range, they are determined to be equal.
298
299**[Positive Example]**
300
301-  Source program
302```
303\#include \<stdio.h\> \#include \<math.h\> \#define EPSILON 1e-6 /
304\* Acceptable error range for the comparison of double-precision floating point numbers \*/
305int main() {
306    double a = 0.3;
307    double b = 0.6;
308    double c = 0.9;
309    if (fabs((a+b)-c) \< EPSILON) {
310        printf("double equal\\n");
311    }
312    return 0;
313}
314```
315
316-  Compiler options
317
318```
319gcc -Wfloat-equal float_equal.c -o out
320```
321
322##### G.C&C++.WARN.15 Enable -Wswitch-default to check whether the **switch** statement has the default branch.
323
324**[Type]** Recommendation
325
326**[Description]** If the **switch** statement does not have the default branch, a compilation warning is generated under the **-Wswitch-default** option.
327
328**[Negative Example]**
329
330-  Source program
331```
332enum TintColor{
333    RED,  DARK_RED,  GREEN,  LIGHT_GREEN
334};
335void Colorize(enum TintColor Color)  {
336    switch (Color)  {
337        case RED:
338            /\* code \*/
339            break;
340        case DARK_RED:
341            break;
342    }
343}
344```
345-  Compiler options
346```
347gcc -Wswitch-default switch_default.c -o out
348```
349-  Compilation result
350```
351warning: switch missing default case [-Wswitch-default] switch (Color)
352```
353
354#### Variables
355
356##### G.C&C++.WARN.16 Enable -Wshadow to check variable coverage.
357
358**[Type]** Recommendation
359
360**[Description]** With the **-Wshadow** option enabled, a warning is generated when local variables overwrite global variables and function parameters. A large number of warnings will be generated when this option is enabled in C++. You can determine whether to enable it based on the actual situation.
361
362**[Negative Example]**
363
364-  Source program
365```
366int num = 0;
367int foo(int a, int b){
368     int num = a + b;
369    return num;
370}
371
372```
373-  Compiler options
374```
375gcc -Wshadow shadow.c -o out
376```
377-  Compilation result
378```
379warning: declaration of 'num' shadows a global declaration [-Wshadow] int num = a + b;
380```
381
382##### G.C&C++.WARN.17 Enable -Wstack-usage=len to set the stack size.
383
384**[Type]** Recommendation
385
386**[Description]** If the stack memory used by a function may exceed the number of bytes specified by **len**, a compilation warning is generated. You can set **len** based on the project requirements.
387
388**[Negative Example]**
389
390-  Source program
391```
392void foo(void) {
393      int arr[1000] = {0};
394      return;
395}
396```
397-  Compiler options
398```
399gcc -Wstack-usage=1000 stack_usage.c -o out
400```
401-  Compilation result
402```
403warning: stack usage is 4012 bytes [-Wstack-usage=] void foo(void) {
404```
405
406##### G.C&C++.WARN.18 Enable -Wframe-larger-than=len to set the stack framework size.
407
408**[Type]** Recommendation
409
410**[Description]** If the stack framework of a function exceeds the number of bytes specified by **len**, a compilation warning is generated. You can set **len** based on the project requirements.
411
412**[Negative Example]**
413
414-  Source program
415```
416void foo(void) {
417    int arr[1000] = {0};
418    return;
419}
420```
421-  Compiler options
422```
423gcc -Wframe-larger-than=1000 stack_usage.c -o out
424```
425-  Compilation result
426```
427warning: the frame size of 4000 bytes is larger than 1000 bytes [-Wframe-larger-than=]
428```
429
430##### G.C&C++.WARN.19 DO NOT enable -Wno-return-local-addr and check the returned local variable address.
431
432**[Type]** Recommendation
433
434**[Description]** If a function returns the address of a local variable, the **-Wreturn-local-addr** warning is generated by default during compilation. Do not enable the **-Wno-return-local-addr** option to suppress this warning.
435
436**[Negative Example]**
437
438-  Source program
439```
440int\* foo() {
441    int a=0;
442    return \&a;
443}
444```
445-  Compiler options
446```
447gcc -Wreturn-local-addr return_local_addr.c -o out
448```
449-  Compilation result
450```
451warning: function returns address of local variable [-Wreturn-local-addr] return \&a;
452```
453
454#### Type Conversion
455
456##### G.C&C++.WARN.20 Enable -Wconversion to check for implicit conversion that results in value changes.
457
458**[Type]** Recommendation
459
460**[Description]** If implicit conversion in the code causes value changes, a compilation warning is generated under the **-Wconversion** option.
461
462Implicit conversions that may cause value changes include: converting a real number with a decimal to an integer, converting an unsigned number to a signed number (or vice versa), and converting a number of a larger type to a smaller type. If explicit conversion is used in the code, no warning is generated under **-Wconversion** during the compilation.
463
464**[Negative Example]**
465
466-  Source program
467```
468int foo(void) {
469    double num = 1.2;
470    return num;
471}
472```
473-  Compiler options
474```
475gcc-Wconversion conversion.c -o out
476```
477-  Compilation result
478```
479warning: conversion from 'double' to 'int' may change value [-Wfloat-conversion] return num;
480```
481
482Do not forcibly convert object pointers from one type to another.
483
484##### G.C&C++.WARN.21 Enable -Wcast-qual to check for missing type qualifier of the target type when the pointer type is forcibly converted.
485
486**[Type]** Recommendation
487
488**[Description]** When the pointer type is forcibly converted, the target type may not contain the type qualifier.
489
490For example, if the const char\* pointer type is forcibly converted to a common char\* pointer type, the type qualifier **const** is not contained. Missing this qualifier may cause modifications to the memory that is not expected to be modified.
491
492**[Negative Example]**
493
494-  Source program
495```
496static char buf[8];
497void foo(){
498    const char\* ptr = buf;
499    char\* q = (char\*)ptr;
500}
501```
502-  Compiler options
503```
504gcc -Wcast-qual cast_qual.c -o out
505```
506-  Compilation result
507```
508warning: cast discards 'const' qualifier from pointer target type [-Wcast-qual] char\* q = (char\*)ptr;
509```
510
511##### G.C&C++.WARN.22 Enable -Wcast-align to check for explicit pointer type conversion to prevent the number of bytes used by the target type for address alignment from increasing.
512
513**[Type]** Recommendation
514
515**[Description]** A warning is generated when the number of bytes used by the target type for address alignment increases due to explicit conversion of a pointer type in the source program. For example, on a machine where an integer is aligned to a two- or four-byte boundary, a warning is generated when char \* is converted to int \*.
516
517#### Arrays
518
519##### G.C&C++.WARN.23 Enable -Wvla to check for variable-length arrays.
520
521**[Type]** Recommendation
522
523**[Description]** If the length of an array is a variable, a compilation warning is generated under the **-Wvla** option.
524
525**[Negative Example]**
526
527-  Source program
528```
529void foo(int len) {
530    int arr[len];
531}
532```
533-  Compiler options
534```
535gcc -Wvla val.c -o out
536```
537-  Compilation result
538```
539warning: ISO C90 forbids variable length array 'arr' [-Wvla] int arr[len];
540```
541
542#### Invalid Code
543
544##### G.C&C++.WARN.24 Enable -Wunused to check for invalid code.
545
546**[Type]** Recommendation
547
548**[Description]** The **-Wunused** option checks for unused variables, functions, parameters, and aliases in the code. This option contains multiple suboptions, as listed below:
549
550- \-Wunused-but-set-variable
551
552- \-Wunused-function
553
554- \-Wunused-label
555
556- \-Wunused-local-typedefs
557
558- \-Wunused-variable
559
560- \-Wunused-value
561
562
563Warnings about formal parameters that are not used in the function are generated only when **-Wextra \-Wunused** or **-Wunused-parameter** is enabled.
564
565**[Negative Example]**
566
567-  Source program
568```
569void foo(void) {
570    int a;
571}
572```
573-  Compiler options
574```
575gcc -Wunused unused.c -o out
576```
577-  Compilation result
578```
579warning: unused variable 'a' [-Wunused-variable] int a;
580```
581
582#### Preprocessing
583
584##### G.C&C++.WARN.25 Enable -Wundef to check for undefined identifiers in the \#if statement of preprocessing directives.
585
586**[Type]** Recommendation
587
588**[Description]** When an undefined identifier appears in the \#if statement, a warning is generated.
589
590**[Negative Example]**
591
592-  Source program
593```
594\#if DEFINE_A_VALUE
595\#endif
596```
597-  Compiler options
598```
599gcc -Wunused unused.c -o out
600```
601
602-  Compilation result
603```
604warning: "DEFINE_A_VALUE" is not defined, evaluates to 0 [-Wundef] \#if DEFINE_A_VALUE
605```
606
607#### Classes
608
609##### G.C&C++.WARN.26 Enable -Wnon-virtual-dtor to check for undefined virtual destructors for the base class.
610
611**[Type]** Recommendation
612
613**[Description]** Destructors of the derived class can be called during polymorphism invocation only when destructors of the base class are virtual.
614
615**[Negative Example]**
616
617-  Source program
618```
619class Base {
620    public: virtual void foo() const = 0;\
621    ~Base() {}
622};
623class Derived: public Base {
624    public: virtual void foo() const {}
625    Derived() {}
626};
627```
628-  Compiler options
629```
630gcc-Wnon-virtual-dtor non_virtual_destructors.cpp -o out
631```
632
633-  Compilation result
634```
635warning: 'class Base' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]
636```
637
638##### G.C&C++.WARN.27 Enable -Wdelete-non-virtual-dtor to check whether the pointer of the base class is used for deletion when no virtual destructor is defined for the base class.
639
640**[Type]** Recommendation
641
642**[Description]** If the pointer of the base class is used for deletion when no virtual destructor is defined for a base class, undefined behavior may occur. Do not enable the **-Wno-delete-non-virtual-dtor** option to suppress this type of warning.
643
644**[Negative Example]**
645
646-  Source program
647```
648class Base {
649    public: virtual void f();
650};
651class Sub: public Base {
652    public: void f(int);
653};
654int main() {
655    Sub\ * sub = new Sub();
656    Base\ * base = sub;
657    delete base;
658}
659```
660-  Compiler options
661```
662gcc--Woverloaded-virtual overloaded_virtual.cpp -o out
663```
664-  Compilation result
665```
666warning: deleting object of polymorphic class type 'Base' which has non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor] delete base;
667```
668
669##### G.C&C++.WARN.28 Enable -Woverloaded-virtual to check for hiding virtual functions of the base class.
670
671**[Type]** Recommendation
672
673**[Description]** A derived class redefines the virtual function of the base class, causing that function to be hidden. If this is the case, a warning is generated when **-Woverloaded-virtual** is enabled.
674
675**[Negative Example]**
676
677-  Source program
678```
679class Base {
680    public: virtual void f();
681};
682class Sub: public Base {
683    public: void f(int);
684};
685```
686-  Compiler options
687```
688gcc--Woverloaded-virtual overloaded_virtual.cpp -o out
689```
690-  Compilation result
691```
692warning: by 'void Sub::f(int)' [-Woverloaded-virtual] void f(int);
693```
694### Security Options
695
696#### Options
697
698##### G.C&C++.SEC.01 Enable the stack protection options.
699
700**[Type]** Requirement
701
702**[Description]**
703
704**User-mode Linux**
705
706Application phase: compiler options
707
708Application scope: relocatable files (.o), dynamic libraries, and executable programs.
709
710Syntax: -fstack-protector-all/-fstack-protector-strong
711
712Description:
713
714In the case of a buffer overflow vulnerability, an attacker can overwrite the return address on the stack to hijack the control flow. When stack protection is enabled, a canary word is inserted between the buffer and the control flow. Generally, this canary word is overwritten when the attacker overwrites the return address. By checking the canary word, you can determine whether an overflow attack occurs.
715
7161\. Enable **-fstack-protector-strong** in GCC 4.9 and later versions.
717
7182\. Enable **-fstack-protector-all** in versions earlier than GCC 4.9.
719
7203\. This feature is not supported in the Wind River Linux 4.3 + MIPS environment.
721
722**Kernel-mode Linux**
723
724Application phase: compiler options
725
726Application scope: kernel mode of the Linux platform
727
728Usage: Enable **CONFIG_CC_STACKPROTECTOR** or **CONFIG_CC_STACKPROTECTOR_STRONG** before kernel compilation.
729
730Description:
731
732In kernel 3.14 and later versions, **CONFIG_CC_STACKPROTECTOR_STRONG** is supported, and **CONFIG_CC_STACKPROTECTOR** (corresponding to **-fstack-protector**) is changed to **CONFIG_CC_STACKPROTECTOR_REGULAR**. In kernel 4.18 and later versions, **CONFIG_CC_STACKPROTECTOR_REGULAR** (corresponding to **-fstack-protector**) is changed to **CONFIG_STACKPROTECTOR**, and **CONFIG_CC_STACKPROTECTOR_STRONG** (corresponding to **-fstack-protector-strong**) is changed to **CONFIG_STACKPROTECTOR_STRONG**.
733
734Exception: You do not need to enable this feature if the OS kernel in use, which must fall into one of the following scenarios, does not support it.
735
7361. The OS version is the latest official version or recommended version.
737
7382. The OS version in a mandatory selection for purposes of product compatibility.
739
7403. The OS version cannot be upgraded due to commercial reasons.
741
742**LiteOS**
743
744Application phase: compiler options
745
746Application scope: LiteOS V200R003C00 and later versions
747
748Syntax: -fstack-protector-all/-fstack-protector-strong
749
750Description:
751
7521. Enable **-fstack-protector-strong** in GCC 4.9 and later versions.
753
7542. Enable **-fstack-protector-all** in versions earlier than GCC 4.9.
755
756Exception: You do not need to enable this feature if the compiler does not provide this option or hardware stack protection is supported, as described below:
757
7581. Versions earlier than IAR 8.20 do not support stack protection.
759
7602. Hardware stack protection is provided. For example, some products in the ARC architecture can provide hardware stack protection, and hardware exceptions are triggered in the case of stack overflow.
761
762##### G.C&C++.SEC.02 Enable the ASLR option.
763
764**[Type]** Requirement
765
766Type for the high address space layout randomization (ASLR) and force ASLR option on the Windows platform: Recommendation
767
768**[Description]**
769
770**User-mode Linux**
771
772a. Run the **echo 2 \>/proc/sys/kernel/randomize_va_space** command to enable the system randomization configuration.
773
774Application phase: runtime system configuration
775
776Application scope: heap, stack, and memory mapping segment (mmap base address, shared libraries, and vDSO page)
777
778Syntax: echo 2 \>/proc/sys/kernel/randomize_va_space
779
780Description:
781
782ASLR is a security technique used to prevent the exploit of buffer overflow vulnerabilities. It randomizes the layout of linear regions such as heaps, stacks, and shared libraries, making it harder for attackers to predict target addresses and preventing them from locating attack code, which leads to reduced overflow attacks. When **randomize_va_space** is set to **1**, the stack, data segment, and vDSO are randomized. When **randomize_va_space** is set to **2**, the heap address is also randomized.
783
784To use the highest level ASLR, set **randomize_va_space** to **2**.
785
786b. Enable the PIC option to randomly load dynamic libraries.
787
788Application phase: compiler options
789
790Application scope: dynamic libraries
791
792Syntax: –fPIC(-fpic)
793
794Description:
795
796The position-independent code (PIC) option implements code segment relocation on a data segment, so the code segment does not change when .so files are being loaded. In this case, all processes share a code segment copy.
797
798Both the **\-fPIC** and **-fpic** options ensure that GCC produces PIC. The only difference is that **-fPIC** produces larger code whereas **-fpic** produces smaller code.
799
800c. Enable the PIE option to randomly load executable files.
801
802Application phase: compile options and link options
803
804Application scope: executable programs
805
806Syntax: –fPIE (-fpie) -pie
807
808Description:
809
810Position-independent executable (PIE) files can be loaded randomly in the same manner as shared libraries during loading and execution. The PIE can effectively reduce the success rate of fixed address attacks and buffer overflow attacks.
811
812(1) Check whether hot patch versions support the PIE options. If not, do not use any PIE option.
813
814(2) **-fPIE** is a compiler option, and **-pie** is a link option.
815
816(3) **-fPIE** produces larger code, whereas **-fpic** produces smaller code.
817
818**LiteOS**
819
820a. Enable random loading of code segments and data segments.
821
822Application phase: compiler options, link options, and runtime system configuration
823
824Application scope: LiteOS V200R003C00 and later versions
825
826Usage: Compile the image into a random image, and then randomly correct the address during image loading.
827
828Description:
829
8301. This feature depends on the bootloader that supports random address loading and depends on the MMU and DDR space.
831
8322. When this feature is enabled, the performance decreases by about 10%.
833
8343. The **-fPIE** and **-pie** options use the Global Offset Table (GOT) to implement address randomization. Both GCC and in-house HCC compilers support this feature.
835
8364. If the cost is high and cannot be implemented, provide specific data to the TMG for review.
837
838Exception: You do not need to enable this feature in the case of product hardware design or startup process restrictions, as described below:
839
8401. XIP scenario, where the system directly runs on the flash memory.
841
8422. ROM-based scenario, that is, all or part of the code is ROM-based and cannot be reloaded.
843
8443. The bootloader does not support random address loading.
845
846b. Enable random loading of dynamic libraries.
847
848Application phase: compiler options
849
850Application scope: LiteOS V200R003C00 and later versions
851
852Syntax: -fPIC
853
854Description: **-fPIC** is used in the dynamic library compilation phase.
855
856##### G.C&C++.SEC.03 Enable GOT RELRO.
857
858**[Type]** Requirement
859
860**[Description]**
861
862**User-mode Linux**
863
864a. Partial RELRO
865
866Application phase: link options
867
868Application scope: dynamic libraries and executable programs
869
870Syntax: -Wl,-z,relro
871
872Description:
873
874A dynamically linked executable and linkable format (ELF) binary uses the GOT to dynamically resolve functions in shared libraries. Attackers can leverage the buffer overflow to modify the function addresses of GOT entries in an attempt to attack the system. By adding the Relocation Read-Only (RELRO) option, you can prevent the GOT from being maliciously overwritten.
875
876b. Full RELRO
877
878Application phase: link options
879
880Application scope: dynamic libraries and executable programs
881
882Syntax: -Wl,-z,now
883
884Description:
885
886After partial RELRO is enabled and then the now option is enabled, full RELRO can be implemented. In other words, **-Wl,-z,relro,-z,now** is used to implement full RELRO. It can defend against Return to Procedural Linkage Table (Ret2PLT) attacks, but not buffer overflow attacks.
887
888If your product uses a large number of functions in shared libraries, applying RELRO will slow down program loading (startup), but it does not affect the runtime performance.
889
890##### G.C&C++.SEC.04 Enable the non-executable stack option/data execution protection option to implement non-executable stack protection.
891
892**[Type]** Requirement
893
894**[Description]**
895
896**User-mode Linux**
897
898Application phase: link options
899
900Application scope: dynamic libraries and executable programs
901
902Syntax: -Wl,-z,noexecstack
903
904Description:
905
9061. If there are nested functions, functional errors may occur. In this case, use **-Wtrampolines** to check the code. The version must be GCC 4.6.4 or later.
9072. Wind River Linux 4.3 does not support this feature.
9083. Wind River Linux 6 + MIPS does not support this feature.
909
910**LiteOS**
911
912Application phase: runtime system configuration
913
914Application scope: LiteOS V200R003C00 and later versions
915
916Usage: The runtime configuration stack cannot be executed, and the data segment (BSS and DATA) cannot be executed.
917
918Description: This feature requires the hardware to support memory protection units such as MMU, MPU, and PMP.
919
920##### G.C&C++.SEC.05 Use the -s option or the strip tool to remove the symbol tables.
921
922**[Type]** Requirement for user-mode Linux and recommendation for other platforms
923
924**[Description]**
925
926**User-mode Linux**
927
928Application phase: link options
929
930Application scope: dynamic libraries and executable programs
931
932Usage: -s (strip tool)
933
934Description:
935
936Symbols play a vital role in the linking process. The essence of a linking process is to link multiple target files together. A symbol can be regarded as the adhesive for linking. The entire linking process is completed based on symbols. After linking is complete, the symbol table will no longer affect the running of executable files. Instead, it can be exploited by attackers. Therefore, deleting the symbol table can help defend against hacker attacks. In addition, it can help reduce the file size.
937
9381. For static libraries, relocatable files (.o) cannot be stripped. Otherwise, compilation errors occur. The symbol table can be removed only for products involving ELF executable files and dynamic libraries.
939
9402. For components and platforms that are delivered only to internal products, a formal mechanism must be provided to instruct downstream products to delete the symbol table in the release phase.
941
9423. Stripping affects the locating of network problems and hot patches. Therefore, the versions before and after stripping must be synchronized in the build process. That is, the versions that are not stripped must be reserved locally for patch making and online commissioning. The following solutions can be used:
943
944    3.1 During compilation, the executor generates executable files and dynamic library versions whose symbol tables are not stripped. The versions are archived to the VMP (CMC) for hot patches.
945
946    3.2 Use the strip tool to delete symbol tables from dynamic libraries and executable files.
947
948    3.3 The executable files and dynamic libraries with symbol tables removed can be compressed to the startup software package.
949
9504. The strip tool and the **-s** option can achieve the same effect of removing the symbol table. If the **-s** option is used, the version will be compiled and built twice. You are advised to use the strip tool before release. The strip level is the default value, for example, stripbin.out.
951
952**LiteOS**
953
954Application phase: link options
955
956Application scope: LiteOS V200R003C00 and later versions
957
958Syntax: -s(strip)
959
960Description: The compilation result of LiteOS products for burning is a .bin file, which does not contain symbol table. Therefore, you are advised not to enable this feature.
961
962##### G.C&C++.SEC.06 Do not use the Run-time Search Path option.
963
964**[Type]** Requirement
965
966**[Description]**
967
968**User-mode Linux**
969
970Application phase: link options
971
972Application scope: dynamic libraries and executable programs
973
974Syntax: -Wl,--disable-new-dtags,--rpath,/libpath1:/libpath2;-Wl,--enable-new-dtags,--rpath,/libpath1:/libpath2
975
976Description:
977
978This option is used to protect against the substitute of the **LD_LIBRARY_PATH** for a dynamic library with the same name. This option specifies a path for the runtime dynamic library search, which has a higher search priority than the path specified by **LD_LIBRARY_PATH**. When an executable file searches for a dynamic library at run time, it first searches the path specified by **--rpath** and then searches the path specified by **LD_LIBRARY_PATH**. In the case **LD_LIBRARY_PATH =[attackpath]**, using this option can effectively prevent against the substitute of the **LD_LIBRARY_PATH** for a dynamic library with the same name. However, this option has limitations. For example, if the specified path is not secure, common users can use malicious programs to replace normal programs in these directories, causing privilege escalation and subsequently resulting in insecure path vulnerabilities.
979
980##### G.C&C++.SEC.07 Enable write protection for code segments and data segments.
981
982**[Type]** Recommendation
983
984**[Description]**
985
986**LiteOS**
987
988a. Configure write protection for code segments and read-only data segments.
989
990Application phase: runtime system configuration
991
992Application scope: LiteOS V200R003C00 and later versions
993
994Usage: The runtime configuration code segment and read-only data segment cannot be modified.
995
996Description: This feature requires the hardware to support memory protection units such as MMU, MPU, and PMP.
997
998##### G.C&C++.SEC.10 Enable the compiler macro FORTIFY_SOURCE to enable the FS option.
999
1000**[Type]** Recommendation
1001
1002**[Description]**
1003
1004**User-mode Linux**
1005
1006Application phase: compiler options
1007
1008Syntax: -D_FORTIFY_SOURCE=2 -O2
1009
1010Description:
1011
1012When a program uses a static buffer with a fixed size, adding this option will allow the compiler or runtime library to check the call of related functions at compile time or run time.
1013
1014In principle, the recommended level is -O2, which delivers a better performance optimization effect than O1. If the product is based on O2, -O1 can be used.
1015
1016Add the option to a branch version first and conduct performance testing. Then determine whether to add the option to the mainline version based on the test result.
1017
1018**LiteOS**
1019
1020Application phase: compiler options
1021
1022Application scope: LiteOS V200R003C00 and later versions
1023
1024Syntax: -D_FORTIFY_SOURCE=2 -O2
1025
1026Description:
1027
10281. The benefits of the option are related to the implementation of the library.
1029
10302. Currently, LiteOS uses the musl library. If the product uses another library that supports related functionalities, enable the option as required.
1031
1032Exception: You do not need to enable this option if the library does not support this feature, as described below:
1033
10341. Setting D_FORTIFY_SOURCE=2 for the musl library does not take effect, which may cause misleading. Therefore, you do not need to enable D_FORTIFY_SOURCE.
1035
1036##### G.C&C++.SEC.11 Enable the ftrapv option to detect integer overflow.
1037
1038**[Type]** Recommendation
1039
1040**[Description]**
1041
1042User-mode Linux and LiteOS
1043
1044Application phase: compiler options
1045
1046Syntax: -ftrapv
1047
1048After the **-ftrapv** option is used, the addition, subtraction, and multiplication operations on signed integers are performed by using functions contained in a GCC library libgcc.c instead of CPU instructions.
1049
1050Using this option greatly affects the performance. You are not advised enabling the option in the release version.
1051
1052##### G.C&C++.SEC.13 Enable the stack check option.
1053
1054**[Level]**
1055
1056Recommendation for user-mode Linux
1057
1058Requirement (disabled) for LiteOS
1059
1060**[Description]**
1061
1062**User-mode Linux**
1063
1064Application phase: compiler options
1065
1066Application scope: relocatable files, dynamic libraries, and executable programs.
1067
1068Syntax: -fstack-check
1069
1070Description:
1071
1072The **stack-check** option checks the stack space in a program at compile time. If the stack space exceeds the alarm threshold, an alarm is generated. Then, an extra instruction is generated in the program to check whether the stack overflows at run time. The **stack-check** option sets a secure buffer at the lowest bottom of each stack. If the stack space applied in the function enters the security buffer, a Storage_Error exception is triggered. However, the generated code does not process exceptions. If an exception is detected, a message is sent to notify the OS. It ensures that the OS can detect stack extension.
1073
1074Using this option greatly affects the performance. You are advised to enable the option in the debug version, but not the release version.
1075
1076Implementation suggestion: optional
1077
1078**LiteOS**
1079
1080Application phase: compiler options
1081
1082Application scope: LiteOS V100R003C00 and later versions
1083
1084Syntax: -fstack-check
1085
1086Description: After the stack check option is enabled, the program may access an invalid address, causing execution exceptions. Therefore, do not enable it on the LiteOS platform.
1087
1088### Optimization Options
1089
1090#### Options
1091
1092##### P.C&C++.01 Select an appropriate optimization level based on the actual test result.
1093
1094**[Description]** Based on the actual test result, try different code optimization options to see if they are really faster for the program.
1095
1096##### G.C&C++.OPT.01 Preferentially select -O2, -Os, and -O3.
1097
1098**[Type]** Recommendation
1099
1100##### G.C&C++.OPT.02 Use -fno-strict-aliasing to disable strict alias optimization when many pointers of different types need to be converted.
1101
1102**[Type]** Recommendation
1103
1104**[Description]** **-O2** of GCC enables **-fstrict-aliasing** for strict alias rule optimization. The compiler assumes that the same memory address will never store different types of data. This optimization option is relatively radical. To avoid optimization issues caused by the conversion between pointers of different types in the code, you can use **-fno-strict-aliasing** to disable the optimization. A good practice is to modify the code to follow strict alias rules.
1105
1106Using the **-fno-strict-aliasing** option may affect product performance. For example, in the test of a performance-sensitive component of a product, the performance of **-O2 \-fno-strict-aliasing** decreases by 9% compared with **-O2**.
1107
1108##### G.C&C++.OPT.03 In the x86/ARM architecture, use -fno-omit-frame-pointer to disable stack frame pointer (SFP) optimization for DOPRA-based products.
1109
1110**[Type]** Recommendation
1111
1112**[Description]** **-fno-omit-frame-pointer**: The -O (-O1) option of GCC
1113enables the **-fomit-frame-pointer** optimization option, that is, removing the frame pointer used during function invoking. This optimization makes the code difficult to debug. You are advised to disable the optimization by using the **-fno-omit-frame-pointer** option.
1114
1115You need to balance performance optimization and debugging information retention.
1116
1117### Code Generation Options
1118
1119#### Options
1120
1121##### G.C&C++.CDG.01 Use -fno-common to check for uninitialized global variables in the data segment of the target file.
1122
1123**[Type]** Requirement
1124
1125**[Description]** With the **-fno-common** option enabled, a warning is generated when an uninitialized global variable placed in the data segment of the target file is declared in two compilation units. Defining multiple temporary global variables increases the difficulty in code maintenance, reduce the linking speed, and consume more space.
1126
1127##### G.C&C++.CDG.02: Use -freg-struct-return to return a struct in the register.
1128
1129**[Type]** Recommendation
1130
1131**[Description]** With the **-freg-struct-return** option, the register returns the struct and union.
1132
1133With the **-fpcc-struct-return** option, the memory instead of the register is used to return a struct and union (either short or long).
1134
1135You are advised to use the register to return the struct and union. For a small struct, this is more efficient than **-fpcc-struct-return**.
1136
1137If neither **-fpcc-struct-return** nor **-freg-struct-return** is used, GNU CC uses the standard rules specified by the target machine. If there is no standard rule, GNU CC uses **-fpcc-struct-return** by default except on the machine where GNU CC is the main compiler. If a standard can be selected, the register return mode is selected.
1138
1139Note that this option affects binary compatibility and should be unified for the entire product.
1140
1141##### G.C&C++.CDG.03 Use -fvisibility=hidden to set the visibility of symbols in the default ELF image to hidden.
1142
1143**[Type]** Recommendation
1144
1145**[Description]** The **-fvisibility=hidden** option makes only APIs in the dynamic library externally visible, effectively implementing binary modularization. This option helps increase the speed of dynamic library linking and loading and prevent symbol conflicts. However, after this option is enabled, the cost of patching the module function needs to be considered because the original global symbol now has the LOCAL attribute, the name needs to be changed when the patch is installed (the DOPRA patch specification has detailed naming rules), and the patch building cost will increase. Balance the benefits against the costs before enabling this option.
1146
1147##### G.C&C++.CDG.04 Use -fstrong-eval-order to enable the expression calculation sequence rule.
1148
1149**[Type]** Recommendation
1150
1151**[Description]** The **-fstrong-eval-order** option determines the calculation sequence of subexpressions based on C++17 specifications. For example, when the option is not enabled,
1152the expression T().m_i = A().B() may generate the evaluation sequence A() T() B(), which is different from that expected. This option is automatically enabled when **-std=c++17** is enabled. However, **-std=c++14** is used in GCC 7.3 by default. You are advised to enable this option explicitly to reduce unexpected behavior.
1153
1154### General Options
1155
1156#### Options
1157
1158##### G.C&C++.OVA.01 Enable the general option -pipe.
1159
1160**[Type]** Recommendation
1161
1162**[Description]** With the **-pipe** option enabled, multiple pipes are concurrently used during compilation to shorten compilation time.
1163
1164### Architecture Options
1165
1166#### Options
1167
1168##### G.C&C++.MD.01 Explicitly specify the following architecture options for embedded software.
1169
11701.  Soft and hard floating points (added or not added based on CPU-supported types)
1171
11722.  Instruction set (such as march=armv7-a and march=armv8-a)
1173
1174**[Type]** Requirement
1175
1176### Link Options
1177
1178#### Options
1179
1180##### G.C&C++.LNK.01 Enable the link options -Wl,-Bsymbolic, -rdynamic, and -Wl,--no-undefined.
1181
1182**[Type]** Recommendation
1183
1184**[Description]** With the **-Wl,-Bsymbolic** option enabled, the symbol with the same name preferentially uses the local .so file to reduce GOT redirections.
1185The **-rdynamic** option resolves the reverse dependency problem of dlopen. The .bin file returns symbol names through addresses. If this option is disabled, backtrace_symbol returns an address that cannot be used for locating. This option increases the size of the .bin file.
1186
1187The **-Wl,--no-undefined** option identifies runtime loading errors in the linking period. If this option is enabled, the linking time is prolonged due to dependency verification in the linking period. If dependency libraries specified by **-l** are incomplete, functional errors may occur. You need to balance between performance and functions.
1188
1189
1190### Debugging Options
1191#### Options
1192
1193##### G.C&C++.DBG.01 DO NOT carry debugging information during version release build.
1194
1195**[Type]** Requirement
1196
1197**[Description]** The debugging information refers to the symbol table and the detailed debugging information table. According to the security regulations, the debugging information is not mandatory for running and should be deleted from the release package. However, the information loss adversely affects maintenance and debugging, such as hot patches, perf analysis, and stack capture.
1198
1199If the **-s** link option is used, no debugging information is generated. Note that the build-id of the component generated by this method is different from that of the rebuilt components without the **-s** option, and therefore it cannot be directly used to locate faults in the GDB. You can also use **objcopy --only-keep-debug \<target\> \<xxx.dbg\>** and **objcopy objcopy --strip-unneeded \<target\>** to separate debugging symbols after linking. In this way, the deliverables do not contain debugging information.
1200
1201If **-g** is enabled in the compilation phase to generate a detailed debugging information table, binary differences may occur in different directories due to the absolute path information of the source code. In this case, you can use **-fdebug-prefix-map=old=new** to map the absolute path to a relative path.
1202
1203### Compiler Macros
1204#### Options
1205
1206##### G.C&C++.PRE.01 Specify a specific purpose of each -D compiler macro and create a list of -D compiler macros.
1207
1208**[Type]** Requirement
1209
1210**[Description]** Each time a -D compiler macro is added, additional testing is required. Verify that the code modifications made on each software -D compiler macro are applicable to other -D compiler macros. First, for all -D compiler macros, software build is required to eliminate compilation errors. Second, complete testing is mandatory for all -D compiler macros.
1211
1212Delete all unused -D compiler macros.
1213
1214### Other
1215#### Options
1216
1217##### G.C&C++.OTH.01 DO NOT use duplicate or inclusion compiler options in a build project.
1218
1219**[Type]** Recommendation
1220
1221**[Description]** Duplicate compiler options cause redundant information and hinder maintenance. If the compiler options have different parameters, the source file may be compiled in a way different than initially expected.
1222
1223Using compiler options with inclusion relationships also causes redundancy. For example, **-Wall** contains more than 40 sub-warning options, and **-O** contains more than 40 sub-optimization options. When they are used together with sub-options, redundancy occurs.
1224
1225**[Negative Example]** A component takes the value of the compiler optimization option **-O** for 7055 times, and multiple **-O** options, for example, **-O2...-O6** and **-O2...-O3**, exist in a build project.
1226
1227\# The use of **-Wall** and **-Waddress** at the same time causes redundancy.
1228
1229gcc -Wall -Waddress -c test.c -o test.o
1230
1231\# The use of **-O** and **-fauto-inc-dec** at the same time causes redundancy.
1232
1233gcc -O -fauto-inc-dec -c test.c -o test.o
1234
1235##### G.C&C++.OTH.02 DO NOT use conflicting options.
1236
1237**[Type]** Recommendation
1238
1239**[Description]** Most **-f** and **-W** have two opposite options,
1240such as **-fname** and **-fno-name**, as well as **-Wname** and **-Wno-name**. If they are referenced at the same time, conflicts occur, which is confusing and inconvenient for maintenance.
1241
1242**[Negative Example]**
1243
1244\# Reference both **-fomit-frame-pointer** and **-fno-omit-frame-pointer**.
1245
1246```
1247set(CMAKE_C_FLAGS "-MD -MF -Wall -save-temps -fverbose-asm -fsigned-char
1248\-fomit-frame-pointer -fno-stack-protector \\
1249
1250\-fno-delete-null-pointer-checks -fno-common -freg-struct-return -O2
1251\-fno-omit-frame-pointer -fno-strength-reduce" )
1252```
1253
1254##### G.C&C++.OTH.03 Compiler options are compiled in the following sequence: optimization levels (such as -O2) + general options + warning options + language options + code generation options + architecture options (MD-dependent options) + optimization options + security options + custom macros.
1255
1256**[Type]** Recommendation
1257
1258**[Description]** Place compiler option sets prior to specific options. For example, write **-Wall** before **-Wformat=2**.
1259
1260**[Positive Example]**
1261
1262```
1263\# Copyright (c) Huawei Technologies Co., Ltd. 2019. All rights reserved.
1264\# toolchain for ARMA15(without FPU)HI1381/HI1215
1265\# cpu_family = arm
1266\# bit_width_in_run = 32
1267\# cpu_core = a15
1268\# compile flags
1269set(CC_OPT_LEVEL "-O2")
1270set(CC_OVERALL_FLAGS "-pipe")
1271set(CC_WARN_FLAGS "-Wall -Wextra -Wdate-time -Wtrampolines -Wfloat-equal
1272\-Wshadow -Wformat=2")
1273set(CC_LANGUAGE_FLAGS "-fsigned-char")
1274set(CC_CDG_FLAGS "-fno-common -freg-struct-return")
1275set(CC_MD_DEPENDENT_FLAGS "-mfloat-abi=soft -march=armv7-a -mtune=cortex-a15")
1276set(CC_OPT_FLAGS "-fno-strict-aliasing -fno-omit-frame-pointer")
1277set(CC_SEC_FLAGS "-fPIC -fstack-protector-strong --param=ssp-buffer-size=4")
1278set(CC_DEFINE_FLAGS "-DXXXXX")
1279set(CC_ALL_OPTIONS "\${CC_OPT_LEVEL} \${CC_OVERALL_FLAGS} \${CC_WARN_FLAGS}
1280\${CC_LANNGUAGE_FLAGS} \\
1281\${CC_CDG_FLAGS} \${CC_MD_DEPENDENT_FLAGS} \${CC_OPT_FLAGS} \${CC_SEC_FLAGS}
1282\${CC_DEFINE_FLAGS}")
1283
1284\# public link flags
1285set(PUBLIC_LNK_FLAGS "-rdynamic -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now")
1286
1287\# link flag for module
1288set(SHARED_LNK_FLAGS "-shared \${PUBLIC_LNK_FLAGS}")
1289set(PIE_EXE_LNK_FLAGS "-pie \${PUBLIC_LNK_FLAGS}")
1290
1291```
1292
1293## Java Compiler Options
1294
1295### Language Level
1296#### Options
1297
1298##### G.JAVA.LANG.01 Use the same Java compiler language level for each delivery unit, and use the same language level as that of the Java version in use.
1299
1300**[Type]** Requirement
1301
1302**[Description]** If the compiler language levels of multiple modules are different, different compiler options need to be configured for these modules. Consequently, the compilation scripts are inconsistent.
1303
1304If the compiler language level corresponding to the Java version is used, a warning is displayed during compilation when the code is not recommended by the Java version. For example, when you use a Java 7 API, which is annotated as @Deprecated and replaced with a new API in Java 8, a warning is display during compilation if the compiler language level 8 is used.
1305
1306### Maven
1307#### Options
1308
1309##### G.JAVA.MAVEN.01 DO NOT use **-X** during version release to avoid generating a large number of debug logs.
1310
1311**[Type]** Requirement
1312
1313**[Description]** **-X** is a debug option. If **-X** is enabled, a large number of debug logs will be generated.
1314
1315### Javac
1316#### Options
1317
1318##### G.JAVA.JAVAC.01 DO NOT use -nowarn, -Xlint:none, or -Xlint:name to suppress all or some javac compilation warnings, and DO NOT use -g:none or -g:[keyword list] to suppress all or some debugging information.
1319
1320**[Type]** Requirement
1321
1322**[Description]** Compilation warnings help detect code defects and risks in advance. Suppressing compilation warnings brings potential risks to code quality. If the **-g:none** or **-g:[keywordlist]** option is used, too little or too much debugging information is generated, which adversely affects code maintainability or reduces operating efficiency.
1323
1324**[Exception]** -Xlint:all,-processing
1325
1326Annotations processed at run time do not require an annotation processor. Such compilation warnings can be suppressed by using the **-processing** parameter of **-Xlint**.
1327
1328##### G.JAVA.JAVAC.02 Use -source, -target, and -Xlint:all, and set showWarnings in maven-compiler-plugin to true.
1329
1330**[Type]** Requirement
1331
1332**[Description]**
1333
1334**\-source** specifies the Java source file version accepted by the compiler.
1335
1336**\-target** specifies the version of the class file generated by the compiler.
1337
1338**\-Xlint:all** enables all recommended compilation warnings.
1339
1340If **showWarnings** is left blank or set to **false**, some compilation warnings cannot be detected.
1341
1342**[Positive Example]**
1343
1344```
1345\<plugin\>
1346
1347\<groupId\>org.apache.maven.plugins\</groupId\>
1348
1349\<artifactId\>maven-compiler-plugin\</artifactId\>
1350
1351\<configuration\>
1352
1353\<source\>1.8\</source\>
1354
1355\<target\>1.8\</target\>
1356
1357\<showWarnings\>true\</showWarnings\>
1358
1359\<compilerArgs\>
1360
1361\<arg\>-Xlint:all\</arg\>
1362
1363\</compilerArgs\>
1364
1365\</configuration\>
1366
1367\</plugin\>
1368
1369```
1370