CC ++ compiler and debugger on Linux

xiaoxiao2021-03-06  44

Http://263.aka.org.cn/lex/lectures/002/lex-2.1.1/compiler.html

1.7 C / C compiler and debugger on Linux

The main options for running GCC / EGCS GCC / EGCS GDB GDB common command GDB uses other programs / library tools (Ar, Objdump, NM, Size, Strings, Strip, ...) creation and shared libraries Use advanced shared library features

1.7.1 Run GCC / EGCS

The most important software development tool in Linux is GCC. GCC is a GNU's C and C compiler. In fact, GCC can compile three languages: C, C and Object C (an object-oriented extension of C language). The C and C source programs can be compiled and connected with the GCC command.

# Demo #: Hello.c

If you have two or a few C source files, you can easily compile, connect, and generate executables using GCC. For example, suppose you have two source files main.c and factorial.c two source files, and now you have to build a program that generates a calculating order.

-----------------------

Listing Factorial.c

-----------------------

#include

#include

INT FACTORIAL (INT N)

{

IF (n <= 1)

Return 1;

Else

RETURN FACTORALEAL (N - 1) * n;

}

-----------------------

-----------------------

List main.c

-----------------------

#include

#include

INT FACTORIAL (INT N);

INT main (int Argc, char ** argv)

{

Int n;

IF (argc <2) {

Printf ("USAGE:% S N / N", Argv [0]);

Return -1;

}

Else {

n = atoi (Argv [1]);

Printf ("Factorial Of% D IS% D. / N", N, Factorial (N));

}

Return 0;

}

-----------------------

Use the following command to compile the generated executable and execute the program:

$ GCC -O Factorial Main.c Factorial.c

$ ./factorial 5

Factorial of 5 IS 120.

GCC can be used simultaneously to compile C processes and C programs. In general, the C compiler is determined by the suffix name of the source file or a C program. In Linux, the suffix of the C source file is called .c, and the suffix of the C source file is .c or .cpp.

However, the GCC command can only compile C source files, and the library that cannot be automatically used automatically and C programs. Therefore, the G command is usually used to complete the compilation and connection of the C program, which automatically calls GCC implementation compilation. Suppose we have a C source file (Hello.c):

#include

Void main (void) {

Cout << "Hello, World!" << Endl;

}

You can call G commands as follows, Connect, and generate executables:

$ G -o Hello Hello.c

$ ./hello

Hello, World!

1.7.2 main options for GCC / EGCS

Table 1-3 Common options for GCC Commands

Option explanation

-ansi only supports ANSI standard C syntax. This option will prohibit certain features of GNU C,

For example, ASM or TypeOf keywords.

-c only compiles and generates a target file.

-Dmacro defines the MacRo macro with a string "1".

-Dmacro = DEFN defines the MacRo macro in the string "DEFN".

-E runs only the C pre-encoder.

-g generate debugging information. The GNU debugger can take advantage of this information.

-Idirectory Specifies the additional header search path Directory.

-LDirectory Specifies the additional library search path Directory.

-Llibrary is searched for the specified library library.

-m486 performs code optimization for 486.

-o file generates a specified output file. When generating an executable file.

-O0 does not optimize.

-O or -o1 optimized generating code.

-O2 is further optimized.

-O3 is further optimized, including inline functions.

-Shared generates shared target files. Usually used when building a shared library.

-STATIC prohibits the use of shared connections.

-Umacro cancels the definition of Macro macros.

-w does not generate any warning information.

-Wall generates all warning information.

# Demo #

Compilation option for MiniGUI

1.7.3 GDB

The GNU debugger is called GDB, which is an interactive tool that works in character mode. In the X WINDOW system,

There is a front-end graphic tool for GDB, called XXGDB. GDB is a powerful debugger that completed the following debugging

task:

* Set breakpoints;

* Monitor the value of the program variable;

* Single step execution of the program;

* Modify the value of the variable.

You must compile the source file with the -g option before you can use the GDB debugger. Can be defined below Makefile

CFLAGS variable:

Cflags = -g

Usually use the following command when running a GDB debugger:

GDB Progname

Type HELP at the GDB prompt, the classification of the command will be listed, and the main categories are:

* aliases: command alias

* Breakpoints: breakpoint definition;

* DATA: Data View;

* Files: Specify and view files;

* INTERNALS: Maintenance command;

* Running: Program execution;

* Stack: Call Stack View;

* Statu: Status View;

* TRACEPOINTS: Tracking program execution. Type the classification name of the command after Help, you can get a detailed list of this class command.

# Deno #

1.7.4 common commands for GDB

Table 1-4 Common GDB Commands

Command explanation

Break Num Sets breakpoints on the specified row.

BT displays all call stack frames. This command can be used to display the call sequence of the function.

CLEAR Deletes the breakpoints set on a specific source file. The usage is: Clear FileName: Num.

Continue continues to perform the program being debugging. This command is used in the program due to processing signals or breakpoints

Causes it to stop running.

Display Expr is displayed for each program to stop the value of the expression. The expression consists of a variable defined by the program.

File File loads the specified executable for debugging.

Help name shows the help information of the specified command.

Info Break displays the current breakpoint list, including the number of times at the breakpoint.

Info files displays details of the debugged file.

INFO FUNC displays all function names.

INFO LOCAL displays local variable information in a function.

INFO PROG displays the execution status of the debugged program.

INFO VAR displays all global and static variable names.

Kill terminates the procedure being debugged.

List Displays the source code segment.

Make Runs the Make tool without exiting GDB.

NEXT performs a row source code forward without single step to enter other functions.

Print EXPR displays the value of Expression EXPR.

1.7.5 GDB Examples

-----------------

List a wrong C source program bugging.c

-----------------

#include

#include

Static char buff [256];

Static char * string;

int main ()

{

Printf ("" please input a string: ");

Gets (string);

Printf ("/ NYOUR STRING IS:% S / N", STRING);

}

-----------------

The above program is very simple, the purpose is to accept the user's input, then print the user's input. This program uses

A STRING that has not been initialized, so after compiling and running, a segment fault error will appear:

$ GCC -O Test -g Test.c

$ ./test

Please Input A String: Asfd

Segmentation Fault (Core Dumped)

In order to find problems in the program, we use GDB and proceed as follows:

1. Run the gdb bugging command to load the bugging executable;

2. Perform the loaded bugging command;

3. Use the where command to view the places where the program is wrong;

4. Use the list command to view the code near the CENS function; 5. The only factor that can cause a gets function error is the variable string. Use the print command to view the value of String;

6. In GDB, we can directly modify the value of the variable, as long as the String takes a legal pointer value,

Therefore, we set breakpoints at the 11th line;

7. The program stopped until the 11th row. At this time, we can use the set variable command to modify the value of the String;

8. Then continue to run, will see the correct program operation results.

# Demo #

1.7.6 Other Programs / Library Tools

Strip:

NM:

Size:

String:

1.7.7 Creating and using a static library

Creating a static library is quite simple. I usually use the AR program to combine some target files (.o).

Become a separate library, then run RANLIB to add some index information to the library.

1.7.8 Creating and using shared libraries

Special compilation and connection options

-D_reentrant causes preprocessor symbol _REENTRANT to be defined, and this symbol activates some macro characteristics.

The -fpic option generates a stand-alone code. Since the library is being transferred when running, this

The option is required, because when compiling, the address of the memory is not known. in case

The library file may not run correctly without using this option.

-shared option tells the compiler to generate shared library code.

-Wl, -soname -wl tells the compiler to pass the back parameters to the connector. And-Soname is specified

Soname of shared library.

# You can copy the library file to any directory collemed in /etc/ld.so.conf, and

ROOT runs LDConfig; or

# Run Export LD_Library_Path = 'PWD', which adds the current path to the library search path.

1.7.9 Use advanced shared library features

LDD tool

LDD is used to display which shared libraries need to be executed, where to find the shared library of shared library.

2. Soname

A very important thing to share libraries is also very difficult concept is Soname - Short for Shared Object Name. This is a name that is embedded in control data for shared library (.so) files. As mentioned earlier, each program has a list of libraries that need to be used. The content of this list is a series of library Soname, as in LDD display, the shared library loader must find this list.

The key function of Soname is that it provides compatibility standards. When you want to upgrade a library in your system, just like Soname of the new library, the Soname of the old library, use the new library to operate normally. This feature makes it easy to upgrade the program and positioning errors for upgrading the shared library under Linux.

In Linux, the application specifies the version of the hoped library by using Soname. The library can also declare by retaining or changing Soname, which versions are compatible, which makes the programmer to get rid of the problem of shared library version conflict.

View / usr / local / lib directory, analyze the relationship between MiniGUI shared library files

3. Shared library loader

When the program is called, the Linux shared library loader (also known as a dynamic connector) is also automatically called. Its role is to ensure that all appropriate versions of the program needed are transferred to memory. The shared library loader name is LD.so or LD-Linux.so, depending on the version of Linux libc, it must use a little external interaction to complete your own work. However, it accepts configuration information in environment variables and configuration files. File /etc/ld.so.conf defines the path to the standard system library. The shared library loader uses it as a search path. To change this setting, you must run the LDConfig tool as root. This will update the /etc/ls.so.cache file, which is actually one of the files used inside the loader.

Many environment variables can be used to control the operation of the shared library loader (Table 1-4 ).

Table 1-4 Shared library loader environment variable

Variable meaning

LD_AOUT_LIBRARY_PATH In addition to not using the A.out binary format, ld_library_path is the same as those in the binary format.

LD_AOUT_PRELOAD is the same as LD_PRELOAD in addition to the A.out binary format.

LD_keepdir only applies to a.out libraries; ignores the directorys specified by them.

LD_LIBRARY_PATH adds other directories to the library search path. Its content should be by colon

The separated list of directory has the same format as the PATH variable of the executable.

If you call the program that set the user ID or process ID, the variable is ignored.

LD_NOWARN is only available for a.out library; when changing the version number is, warning information is issued.

LD_PRELOAD first loads the user-defined library so that they have the opportunity to overwrite or redefine the standard library.

Use spaces to separate multiple portals. For programs set by the user ID or process ID,

Only the marked library is first loaded. Specify in /etc/ld.so.perload

The global version number, the file does not comply with this limit.

4. Using DLOPEN

Another powerful library function is DLOPEN (). This function will open a new library and put it into memory. This function is mainly used to load symbols in the library, which is not known when compiling. For example, the Apache Web server uses this function to load modules during operation, which provides additional capabilities. A configuration file controls the process of loading the module. This mechanism does not need to be recompiled when adding or deleting a module in the system.

You can use DLOPEN () in your own program. DLOPEN () is defined in DLFCN.H and implemented in the DL library. It requires two parameters: a file name and a logo. The file name can be Soname in the library we have learned. The logo indicates whether the library is calculated immediately. If set to RTLD_NOW, calculate immediately; if it is set to RTLD_LAZY, it is calculated when needed. Alternatively, RTLD_GLOBAL can be specified, which makes those libraries that are only loaded later.

When the library is loaded, the handle returned by DLOPEN () can be used as the first parameter to DLSYM () to obtain the address in the library. With this address, you can get a pointer to a specific function in the library, and call the corresponding function in the loader.

转载请注明原文地址:https://www.9cbs.com/read-53357.html

New Post(0)