




已阅读5页,还剩6页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
An Introduction to GCC: for the GNU Compilers gcc and g+读书笔记Chapter 2:1. Compile a C programa) gcc -Wall hello.c -o helloi. Wall: show all warning & error. It is recommended that you always use this!ii. o: This option is usually given as the last argument on the command line. If it is omitted, the output is written to a default le called *.out.b) Error debugging:i. The messages produced by GCC always have the form le: line-number: message.2. Compiling multiple source lesa) Difference between #include FILE.h and #include i. #include FILE.h Searches in the current directory first then the system header file directory.ii. #include only searches in the system header file directory.b) gcc -Wall main.c hello_fn.c -o newhelloi. Note that hello.h will be included automatically.3. Compiling les independentlya) Why: If a program is stored in a single le then any change to an individual function requires the whole program to be recompiled to produce a new executable.b) The source les are compiled separately and then linked togethera two stage process.i. First stage: .o, an object file.ii. Second stage: the object les are merged together by a separate program called the linker.c) Creating object les from source lesi. gcc -Wall -c main.c-c: compile a source file into an object fileii. Containing the machine code for the main function, has an external reference to hello(), but the exact memory address is not decided. iii. No need to add o optioniv. No need to put the header le hello.h on the command line,d) Creating executables from object lesi. gcc main.o hello_fn.o -o helloii. No need to use the -Wall warning option: file has been compiled.iii. Fails only if there are references which cannot be resolvede) Link order of object lesi. gcc main.o hello_fn.o -o helloii. Object le which contains the denition of a function should appear after any les which call that function.f) Recompiling and relinkingi. If the prototype of a function has changed, it is necessary to modify and recompile all of the other source les which use it.ii. Linking is faster than compilationg) Linking with external librariesi. The most common use of libraries is to provide system functions.ii. Libraries are typically stored in special archive les with the extension .a, referred to as static librariesiii. Using ar command to create a static libraryiv. The default library file is lib.a, when we referred other function, such as math.h, we will need libm.a v. gcc -Wall calc.c -lm -o calcvi. The compiler option -lNAME will attempt to link object les with a library le libNAME.a in the standard library directories.h) Link order of librariesi. Containing the denition of a function should appear after any source les or object les which use it.ii. A library which calls an external function dened in another library should appear before the library containing the function.iii. gcc -Wall data.c -lglpk -lmlibglpk.a calls functions in libm.ai) Using library header file: If you wrongly omit the include header file, you can only detect this error by WallChapter 3: compilation options1. Setting search pathsa) By default, gcc searchesi. The following directories for header les:1. /usr/local/include/2. /usr/include/ii. The following directories for libraries:1. /usr/local/lib/2. /usr/lib/iii. A header le found in /usr/local/include takes precedence over a le with the same name in /usr/include.iv. The compiler options -I and -L add new directories to the beginning of the include path and library search path respectively.b) Search path examplei. gcc -Wall -I/opt/gdbm-1.8.3/include -L/opt/gdbm-1.8.3/lib dbmain.c lgdbm-I: add new directory to the header file search set.-L: add new directory to the library search set.ii. You should never place the absolute paths of header les in #include statements in your source code, as this will prevent the program from compiling on other systemsc) Environment variablesi. Set in .bash_profileii. Additional directories can be added to the include path using the environment variable C_INCLUDE_PATH (for C header les) or CPLUS_INCLUDE_PATH (for C+ header les).iii. C_INCLUDE_PATH=/opt/gdbm-1.8.3/includeC_INCLUDE_PATH=.:/opt/gdbm-1.8.3/include:/net/includeexport C_INCLUDE_PATHLIBRARY_PATH=/opt/gdbm-1.8.3/libexport LIBRARY_PATHd) Extended search pathsi. gcc -I. -I/opt/gdbm-1.8.3/include -I/net/include -L. -L/opt/gdbm-1.8.3/lib -L/net/lib Add multiple search pathse) Exact search order.i. Command-line options -I and -L, from left to rightii. Directories specied by environment variables, such as C_INCLUDE_PATH and LIBRARY_PATHiii. Default system directories2. Shared libraries and static librariesa) Static librariesi. .a lesii. When a program is linked against a static library, the machine code from the object les for any external functions used by the program is copied from the library into the nal executableb) Shared librariesi. extension .soii. An executable le linked against a shared library contains only a small table of the functions it requires.iii. Before the executable le starts running, the machine code for the external functions is copied into memory from the shared library le on disk by the operating systemiv. Dynamic linking makes executable les smaller and saves disk space, because one copy of a library can be shared between multiple programs.v. Shared libraries make it possible to update a library without recompiling the programs which use itc) gcc compiles programs to use shared libraries by default on most systems, if they are availabled) By default the loader searches for shared libraries only in a predened set of system directories, such as /usr/local/lib and /usr/libe) LD_LIBRARY_PATH=/opt/gdbm-1.8.3/libexport LD_LIBRARY_PATHf) gcc -Wall -static -I/opt/gdbm-1.8.3/include/ -L/opt/gdbm-1.8.3/lib/ dbmain.c -lgdbm-static: force static linkingg) gcc -Wall -I/opt/gdbm-1.8.3/include dbmain.c /opt/gdbm-1.8.3/lib/libgdbm.soLink directly with individual library les by specifying the full path to the library on the command line3. C language standardsa) ANSI/ISOi. gcc -Wall -ansi ansi.c-ansi: use ansi. This allows programs written for ANSI/ISO C to be compiled without any unwanted eects from GNU extensions.b) Strict ANSI/ISOi. gcc -Wall -ansi -pedantic gnuarray.c-pedantic: gcc to reject all GNU C extensions, not just those that are incompatible with the ANSI/ISO standard. ii. This helps you to write portable programs which follow the ANSI/ISO standard.c) Selecting specic standardsi. -std=c89 or -std=iso9899:1990Std9899ii. -std=iso9899:199409Add internationalization support: languageiii. -std=c99 or -std=iso9899:1999Std99iv. -std=gnu89 and -std=gnu99.c language standard + GNU extensiond) Warning options in Walli. -Wcomment (included in -Wall)This option warns about nested comments.ii. -Wformat (included in -Wall)This option warns about the incorrect use of format strings in functions such as printf and scanf, where the format specier does not agree with the type of the corresponding function argument.iii. -Wunused (included in -Wall) This option warns about unused variables.iv. -Wimplicit (included in -Wall)This option warns about any functions that are used without being declared. The most common reason for a function to be used without being declared is forgetting to include a header le.v. -Wreturn-type (included in -Wall)This option warns about functions that are dened without a return type but not declared void.e) Additional warning optionsi. They are not included in -Wall because they only indicate possibly problematic or “suspicious” codeii. It is more appropriate to use them periodically and review the results, checking for anything unexpected, or to enable them for some programs or les.iii. -WThis is a general option similar to -Wall which warns about a selection of common programming errorsIn practice, the options -W and -Wall are normally used together.iv. -Werror Changes the default behavior by converting warnings into errors, stopping the compilation whenever a warning occurs.v. -WconversionThis option warns about implicit type conversions that could cause unexpected results. For example: unsigned int x = -1;vi. -Wshadow This option warns about the redeclaration of a variable name in a scope where it has already been declared.vii. -Wcast-qualThis option warns about pointers that are cast to remove a type qualier, such as const.viii. -WtraditionalThis option warns about parts of the code which would be interpreted dierently by an ANSI/ISO compiler and a “traditional” pre-ANSI compiler.Chapter 4: Using the preprocessor1. Dening macrosa) gcc -Wall -DTEST dtest.c-DTEST: define a macro called TEST and assign 1 as its value.The gcc option -DNAME denes a preprocessor macro NAME from the command line.2. Origin of the macrosa) Specied on the command line with the option -D, b) In a source le (or library header le) with #define.c) Automatically dened by the compilerthese typically use a reserved namespace beginning with a double-underscore prex _.3. Macros with valuesa) This value is inserted into the source code at each point where the macro occursb) Note that macros are not expanded inside stringsc) gcc -Wall -DNUM=100 dtestval.cThe -D command-line option can be used in the form -DNAME=VALUE.d) Note that it is a good idea to surround macros by parentheses whenever they are part of an expression.e) A macro can be dened to a empty value using quotes on the command line, -DNAME=4. Preprocessing source lesa) gcc -E test.c-E option: Use C preprocessor to deal with the source file.b) The preprocessor also inserts lines recording the source le and line numbers in the form # line-number source-file, to aid in debugging. Do not aect the program itselfc) Example:Source file: #include Int main (void)printf (Hello, world!n);return 0;Preprocessed file: # 1 hello.c# 1 /usr/include/stdio.h 1 3extern FILE *stdin;extern FILE *stdout;extern FILE *stderr;extern int fprintf (FILE * _stream,const char * _format, .) ;extern int printf (const char * _format, .) ; . additional declarations . # 1 hello.c 2intmain (void)printf (Hello, world!n);return 0;d) gcc -c -save-temps hello.c-save-temps: saves .s assembly les and .o object les in addition to preprocessed .i preprocessed les.Chapter 5: Compiling for debugging1. -g debug optiona) Store additional debugging information in object les and executables.b) This debugging information allows errors to be traced back from a specic machine instruction to the corresponding line in the original source le.c) It also allows the execution of a program to be traced in a debuggerd) Using a debugger also allows the values of variables to be examined while the program is running.2. Examining core lesa) Whenever the error message core dumped is displayed, the operating system should produce a le called core in the current directory which contains the in-memory state of the program at the time it crashed.i. The line where the program stopsii. The values of the variables at that time.b) gcc -Wall -g null.cAdd g to trace the fail error.gdb EXECUTABLE-FILE CORE-FILECore les can be loaded into the GNU Debugger gdb. Noted that it is not possible to debug a core le without the corresponding source file.(gdb) print VARIABLE_NAMEc) Displaying a backtrace(gdb) backtrace#0 0x080483ed in a (p=0x0) at null.c:13#1 0x080483d9 in main () at null.c:7Show the function calls and arguments up to the current point of execution.d) It is possible to move to dierent levels in the stack trace, and examine their variables, using the debugger commands up and downChapter 6: Compiling with optimization1. GCC is an optimizing compiler. It provides a wide range of options which aim to increase the speed, or reduce the size, of the executable les it generates.2. Source-level optimizationa) Common subexpression eliminationi. Computing an expression in the source code with fewer instructions, by reusing already-computed results.ii. Example: x = cos(v)*(1+sin(u/2) + sin(w)*(1-sin(u/2)t = sin(u/2)x = cos(v)*(1+t) + sin(w)*(1-t)b) Function inlining eliminates this overhead by replacing calls to a function by the code of the function itself (known as placing the code in-line).i. It can become signicant only when there are functions which contain relatively few instructionsii. Inlining is always favorable if there is only one point of invocation of a functionc) Example: for (i = 0; i 1000000; i+)double t = (i + 0.5); /* temporary variable */sum += t * t;Eliminating the function call and performing the multiplication in-lineallows the loop to run with maximum eciencyd) The inline keyword can be used to request explicitly that a specic function should be inlined wherever possible, including its use in other les.3. Speed-space tradeosa) Optimizations with a speed-space tradeo can also be used to make an executable smaller, at the expense of making it run slower.b) Loop unrollingmore ecient way to write the same code is simply to unroll the loop and execute the assignments directly:y0 = 0;y1 = 1;y2 = 2;y3 = 3;y4 = 4;y5 = 5;y6 = 6;y7 = 7;c) Loop unrolling is also possible when the upper bound of the loop is unknown, provided the start and end conditions are handled correctly for (i = 0; i (n % 2); i+)yi = i;for ( ; i + 1 &1 | more2. Version numbersa) gcc version3. v: Verbose compilationa) gcc -v -Wall hello.cChapter 10: Compiler-related tools1. Creating a library with the GNU archivera) ar cr LIB_NAME OBJECT_FILENAME1 OBJECT_FILENAME2cr: create and replaceb) ar t LIB_NAMEA “table of contents” option t to list the object les in an existing libraryc) gcc -Wall main.c libhello.a -o hello2. Using the proler gprofa) A useful tool for measuring the performance of a programb) It records the number of calls to each function and the amount of time spent there, on a per-function basis.c) To use proling, the program must be compiled and linked with the -pg proling option:gcc -Wall -c -pg collatz.cgcc -Wall -pg collatz.ogprof a.outIf the program consists of more than one source le then the -pg option should be used when compiling each source le, and used again when linking the object les to create the nal executable3. Coverage testing with gcova) The GNU coverage testing tool gcov analyses the number of times each line of a program is executed during a runb) Combined with proling information from gprof the information from coverage testing allows eorts to speed up a program to be concentrated on specic lines of the source code.c) gcc -Wall -fprofile-arcs -ftest-coverage cov.cThe executable must then be run to create the coverage data, the data from the run is written to several les with the extensions .bb, .bbg and .da respectively in the current directory.gcov cov.cLines which were not executed are marked with hashes #Chapter 11: How the compiler works1. preprocessing (to expand macros)i. cpp hello.c hello.i2. compilation (from source code to assembly language)i. gcc -Wall -S hello.i-S instructs gcc to convert the preprocessed C source code to assembly language wit
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 设计考试题及答案
- 中兽医基础知到智慧树答案
- 中外文明交流史知到智慧树答案
- 居民健康档案管理培训考核试题(含答案)
- 肺结核病患者健康管理培训试题及答案
- 从生产中谈猪病毒性腹泻的防控专题培训考试试题(附答案)
- 2025度酒店客房卫生间改造合同协议书
- 2025年度立体停车库设计与施工合同
- 2025版建筑机械设备租赁与售后服务合同范文
- 2025年新型城镇化包工不包料安置房建设合同
- 六年级家长会课件
- 2025年安徽省淮南市【辅警协警】笔试模拟考试题(含答案)
- T-SCSTA001-2025《四川省好住房评价标准》
- 普通话声母资料
- 《测量降水量》教学课件
- 生态学基本原理解析课件
- 煤灰清理施工方案
- 《大学生军事理论教程》第三章
- 黄遵宪年谱长编(上下册):国家社科基金后期资助项目
- 均值X-R极差分析控制图(自动测算表)
- 体力劳动工作管理程序
评论
0/150
提交评论