Linux programming environment

Source: Internet
Author: User
Tags one more line print format
Linux programming environment I. vim

The vim editor can be divided into three modes: Command mode, insert mode, and baseline mode, as shown in the diagram of mutual conversion between Vim modes.

Command mode: controls the movement of the screen cursor, deletes, copies, and other text edits (the [Del] key and [Backspace] key are not used), and enters the insert mode, or return to the row mode.

Insert mode: You can enter text only in insert mode. Press the [Esc] key to return to the command line mode. Many Vim editor users want to input the content as soon as they open Vim, but this cannot be done because the Vim editor is in command mode when it is just started.

Baseline mode: Save the file or exit Vim. You can also set the editing environment and compile the file, such as listing the row number and searching for strings.

It demonstrates switching between the three modes.

 

In command mode, the following common commands are available:

  1. Insert

A // Add text to the right of the current cursor position

I // Add text to the left of the current cursor position

A // Add text at the end of the current row

I // Add text at the beginning of the current line (the beginning of a non-null character)

O // create a new row above the current row

  • // Create a new row under the current row

 

  1. Delete

X // Delete the current character

Nx // Delete n characters starting from the cursor

Dw // Delete slaveThe cursor starts to the end of a word., ActuallyCut

Dd // Delete the current row and cut

Ndd // Delete n rows, including the current row, and cut

  1. Copy

Yy // copy the current row to the cache.

Nyy // copy n rows down the current row to the buffer zone.

Yw // copy the characters starting from the cursor to the end of the word.

Nyw // copy the n words starting from the cursor.

Y ^ // copy the content from the cursor to the beginning of the line.

Y $ // copy the content from the cursor to the end of the row.

  1. Paste

P (lower case) // paste the content in the clipboard after the cursor.

P (uppercase) // paste the content in the clipboard before the cursor.

  1. Replace

R // Replace (overwrite) The current character

R // Replace (overwrite) The current cursor position and subsequent text

  1. Positioning

H, j, k, l // up, down, left, right can also be used on the keyboard direction keys.

N + // jump n rows down

N-// jump n rows up

NG // jump to the row whose row number is n

G // jump to the bottom of the file

Gg // jump to the file header

Ctrl-f // click the next page

Ctrl-B // flip the page

^ // Move the cursor to the beginning of the line.

$ // Move the cursor to the end of the row.

 

  1. Search Text

/Vpser // search for a vpser string under the cursor

? Vpser // search for a vpser string from the cursor

N // search down

N // search up

  1. Replace

: S/old/new // replace the old

: S/old/new/g // replace all the old in the row with new

: N, m s/old/new/g // replace all the old values from N to m with new

: % S/old/new/g // replace all old files in the current file with new

Note when replacing, add'G'Indicates the involvedLineAll matches in, if not added'G'Replace the first matched in the row,%It is equivalent to all rows.

  1. Undo operation

U // undo the previous operation

U // undo all operations on the current row

  1. Merge

J // merge the row where the cursor is located and the next row as one line (still in command mode)

Of course, VIM also has many common commands, which need to be summarized in future use.

Ii. makefile

For a single source file project, we can execute it step by step through the g ++ command in the command line, such as the source file test. cpp, and finally generate the executable file test.

Run the following command in shell:

$ G ++-c test. cpp generates test. o

$ G ++-o test. o generate the executable file test

If the project has two source files, test. cpp test2.cpp, you need to add one more line for compilation. The process may be complicated in the following situations:

(1) Many source files

(2) Many library files are required.

(3) The g ++ Command requires many parameters.

(4) The dependency between files becomes complex.

(5) When you need to modify a source file

When these situations occur, it is inconvenient to repeat them from the command line. makefile can simplify our work according to rules and dependencies. During file modification, you only need to input the make or gmake command. In general, the makefile structure is:

 

For example, the step for generating test. o can be written

 

In addition, makefile can also define pseudo targets. For example, clean is the most common target, which is used to clean generated temporary and executable files. The following is a simple and complete makefile file.

 

Run $ make to generate the test file.

Run $ make clean to clear the target and executable files.

Makefile also provides many convenient syntaxes, such as macro replacement and functions.

 

For a project, the makefile is concise, because all the commands for generating the target file require only one line, and a SRCFILE may be equivalent to many source files. CFLAGS replaces some compilation options. After the wildcard function and wildcard * are used, $ (wildcard *. cpp) is equivalent to all the source files in the current directory. Similarly, patsubst is replaced by format. In row 7th, all. cpp in the SRCFILE macro is replaced with. o, which is exactly all the target files we need. 12. Lines 13 compile the cpp files in the directory one by one. When we need to modify, we only need to modify a few parts. For example, to add Werror to the compilation option, we only need to modify the third line. Of course, a good makefile file also requires proper comments. makefile uses the '#' symbol for row comments.

III. g ++

G ++ is the gnu c ++ compiler. It takes four steps to compile:

  1. Pre-processing: generate the. I file [pre-processor cpp]
  2. Convert the pre-processed file into an assembly language to generate the file. s [compiler egcs]
  3. Generate. o files from assembly to target code (machine code) [assembler as]
  4. Connect the target code to generate an executable program [linker ld]

In our daily use process, the first three steps are completed in one step. For example

$ G ++-c test. cpp

You can directly generate test. o. When using g ++, you often need to add some options as needed. The common options and explanations are as follows:

-G/-ggdb-g is used to generate debugging information during compilation. gdb debugging can be used only when this option is added to generate executable files, -The ggdb option allows the compilation process to generate as much debugging information as possible.

-O0/-O1/-O2/-O3 this is the four optimization levels of the compiler, increasing from left to right.

-Wall is the abbreviation of warn all. It displays all warning information that g ++ can tell us.

-Werror converts all warnings into errors, that is, the command fails to be executed and is used in combination with-Wall.

-Wunused-parameter: a warning message is generated when the function-defined parameters are not used in the function.

-Wformat: This option is used to check whether the format string is correct when functions such as printf and scanf are called. If not, a warning is generated. This option is already included in-Wall. For example, printf ("abc \ n", I );

-Wconversion some type conversions generate warning information when a value changes, such as conversion between floating point and fixed point, there is also an implicit conversion from a negative integer to a non-negative type (for example, unsigned int x =-1 ). In practice, it seems that the same warning is reported if this option is not added.

-Wdeprecated generates a warning when using obsolete or obsolete files. For example, the header file iostream. h is used in the c ++ program.

-Finline-functions this option embeds all the code of all simple functions into the caller's code. If you embed code into all calls to a given function, if the function is declared as a static function, the function will not be output as assembly code. This option takes effect only under-O3 optimization.

Iv. gdb

In general, GDB helps you complete the following four functions:

  1. Start your program and run it as needed according to your custom requirements.
  2. Allows the program to be debugged to stop at the breakpoint you specified. (The breakpoint can be a conditional expression)
  3. When the program is stopped, you can check what happens in your program.
  4. Dynamically change the execution environment of your program.

Common functions and related commands are as follows:

Start gdb:$ Gdb $ file test or $ gdb test

Exit gdb:$ Quit

Run the program:$ Run

View information:$ Info

View breakpoint information: $ info break

View the observation point information: $ info watchpoint

View the current source program: $ info source

View stack information: $ info stack

View the current parameter: $ info args

List A source program:$ List

List A function: $ list

Displays a source code in the middle of a behavior of the current source file: $ list LINENUM

The previous display continued: $ list

Show the source code before the previous time: $ list-

Program for displaying another file: $ list FILENAME or $ list FILENAME: LINENUM

Breakpoint operation:$ Break

Set a breakpoint at the function entry: $ break

Set a breakpoint in a row of the current source file: $ break LINENUM

Set the breakpoint: $ break FILENAME: LINENUM on a line of another source file

Enable breakpoint: $ enable 2

Disable breakpoint: $ disable 2

Clear breakpoint: $ delete 2

Observation Point Operation

$ Watch EXPR

We know that the breakpoint is interrupted when the program executes a code, while the observation point is that the program is interrupted when it accesses a storage unit. If we do not know where a storage unit is modified, this is especially useful for observation points.

$ Rwatch expr:

Use expr as the expression to set a breakpoint. When expr is read by the program, the program is suspended by GDB;

$ Awatch expr:

Use expr as the expression to set an observation point. When expr is read and written, GDB suspends the program.

Enter the next statementNext step can enter the Function

Exit Function, Finish

Thread operation

A. Thread thread_no: this command is used to switch between threads and set the thread number thread_no (thread number set by GDB) to the current thread;

B. info threads: query the summary of the status of all threads owned by the current process. GDB is displayed in sequence:

A. Thread number: the sequence number set by GDB for the thread in the debugging process;

B. The thread ID of the target system;

3. Current stack information of this thread;

Some threads with a sign '*' indicate that the thread is the current thread;

C. Thread apply [thread_no] [all] ARGs: this command is used to provide commands to threads;

View VariablesThe print command for checking the memory value is X, and X indicates examine. The usage is as follows:

X/NFU ADDR

N indicates the number of duplicates, F indicates the output format, and u indicates the size of each data unit. U can take the following values:

B: byte)

H: double-byte value

W: Four-byte value

G: octal value

Therefore, the preceding command can be used to explain that n u values are displayed in the F format starting from the ADDR address. For example:

X/4ub 0X4000

Four bytes (B), 0x4003, 0 x, 0 x, 0 x are displayed in the unsigned decimal integer format (u. By default, the output format depends on its data type. However, you can change the output format. When you use the print command, you can use a/F parameter to select the print format of the output. F can be the following values:

'X' hexadecimal integer format

'D' signed decimal integer format

'U' unsigned decimal integer format

'F' Floating Point Number Format

For example, char input [5];

(GDB) x/7B Input

The X command prints the content of the specified storage unit. 7b is the print format, B indicates a group of each byte, 7 indicates printing 7 groups, and 7 bytes are printed consecutively starting from the first byte of the input array.

Stack Switching

BT view stack information

Up N up N layers

Down n down N layers

Frame prints the following information: the stack layer number, the current function name, function parameter value, the file and row number of the function, and the statement executed by the function.

Debug core files with gdb

Core dump is also called core dump. When an exception occurs during the program running and the program exits abnormally, the operating system stores the current memory status of the program in a core file, which is called core dump. (In Linux, if the memory is out of bounds, it will receive the SIGSEGV signal and then core dump)

In the process of running the program, sometimes we encounter a segment fault (segment error) error. This seems difficult because there is no stack or trace information output. Errors of this type are often related to pointer operations. It is often possible to locate in this way.

Possible causes of segment fault:

1. Memory Access out of bounds

A) array access out of bounds due to incorrect subscript

B) when searching for a string, the string Terminator is used to determine whether the string ends. However, the string does not use the terminator normally.

C) use strcpy, strcat, sprintf, strcmp, strcasecmp, and other string operation functions to read/write the target string. Functions such as strncpy, strlcpy, strncat, strlcat, snprintf, strncmp, and strncasecmp should be used to prevent read/write from being out of bounds.

2. multi-threaded programs use functions with unsafe threads.

3. data read and write with multiple threads is not locked.

For global data that will be accessed by multiple threads at the same time, pay attention to lock protection, otherwise it will easily cause core dump

4. Invalid Pointer

A) Use a null pointer.

B) Use Pointer conversion at will. A pointer pointing to a memory segment, unless it is determined that the memory is originally allocated to a structure or type, or an array of this structure or type, otherwise, instead of converting it to a pointer of this structure or type, you should copy this memory to a structure or type and then access this structure or type. This is because if the starting address of this memory segment is not aligned according to this structure or type, it is easy to access it because of Bus Error and core dump.

5. Stack Overflow

Do not use large local variables (because all local variables are allocated on the stack). This can easily cause stack overflow, damage the stack and heap structure of the system, and cause inexplicable errors.

 

Configure the operating system to generate core files

Run the ulimit command to check whether the dump core function is supported. You can use ulimit-C or ulimit-a to view the Core File Size configuration. If it is 0, dump core is disabled. You can enable it through ulimit-C unlimited. If a segment error occurs but no core dump exists, the system prohibits the generation of core files.

Solution:

$ Ulimit-C unlimited (only valid for the current Shell Process)

Or in ~ /. Add bashrc: ulimit-C unlimited (once and for all)

# Ulimit-C

0

$ Ulimit-

Core File size (blocks,-C) 0

Data seg size (Kbytes,-d) Unlimited

File size (blocks,-f) Unlimited

Use GDB to view core files

After a core dump occurs, use GDB to view the content of the core file to locate the line that causes the core dump in the file.

$ GDB [exec file] [core file]

Example: $ GDB./test. Core

Use bt to view the call stack.

 

V. twiki

This part feels familiar after several attempts on the wiki.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.