Linux development tools (including gdb debugging tutorial)


img

Linux development tools (including gdb debugging tutorial)

1. Linux package manager yum

  • What is a software package?

    To install software underLinux, a common method is to download the source code of the program and compile it to obtain an executable program. But this is too troublesome, so some people compile some commonly used software in advance and make it into a software package (which can be understood as an installation program onwindows) and put it on a server (Alibaba Cloud, Tencent Cloud , Baidu Cloud, etc.), you can easily obtain this compiled software package through the package manager and install it directly. The software package and the software package manager are like "App" And "app store" such relationship.

    yum(Yellow dog Updater, Modified) is a very commonly used package manager under Linux. Mainly used in Fedora, RedHat, Centos and other distributions.

  • Viewyum’s surroundings — yum’s entire ecological issues

    There are three questions here:

    1,yumHow to know the address and download link of the target server?

    Answer: There is a directory underyum. There is a file in this directory. In this file There is the address and download link of the target server server. /etc/yum.repos.d/CentOS-Base.repo

    2. Who provides cloud services?

    Answer: Because thisLinux was developed by a foreign team, the resourcesLinux are all abroad. But if we need to access a foreign network every time we download this resource (commonly known as circumventing the firewall), the speed will be very slow. Therefore, many domestic companies will mirror this foreign resource for Chinese people to use, and the access speed in China will be faster. More convenient to use. The more famous ones are NetEase’s 163, Tsinghua University, and Alibaba Cloud’s mirror websites.

    3. Who provides the software?

    Answer:Linux’s software mainly comes from various distributions. These distributions can be officially maintained, such as UbuntuBehindCanonical, and they have a team to maintain the core software packages, such asLinuxKernel, desktop environment and various commonly used software, etc. At the same time, there are also community-maintained distributions, such as on Fedora. The community maintains software that is not included in the official software repositories. These software can be used to share and communicate, build community, create value, learn and educate. RPM Fusion

  • About rzsz

    This tool is used to transfer files between the windows machine and the remote Linux machine via XShell. After installation, you can upload files by dragging and dropping

  • Precautions

    All operations on yum must ensure that the host (virtual machine) network is open!!! This can be verified through the ping command

    ping www.baidu.com

    Arrangement ctrl+CStop

  • View packages

    Use the yum list command to list the current software packages. Since the number of packages may be very large, here we need to use the grep command to filter out only the packages we are interested in. For example:
    yum list | grep lrzsz

    • Software package name: major version number. minor version number. source program release number - software package release number. host platform. cpu architecture.
    • The "x86_64" suffix indicates the installation package for 64-bit systems, and the "i686" suffix indicates the installation package for 32-bit systems. When selecting the package, it must match the system.
    • "el7" indicates the version of the operating system distribution. "el7" means centos7/redhat7. "el6" means centos6/redhat6.
    • In the last column, os represents the name of the "operating system".
  • How to install software

    • Ordinary usesudo yum install 软件名称
    • root user:yum install 软件名称

    yumIt will automatically find which software packages need to be downloaded. At this time, hit "y" to confirm the installation. The word "complete" appears, indicating that the installation is complete.

    yumYou can only install one software before installing another. While yum is installing a software, if you try to yum install another software, yum an error will be reported.

  • How to remove software

    • Ordinary usesudo yum remove 软件名称
    • root user:yum remove 软件名称

    Be carefulremove,Notuninstall.


2. Linux development tools

2.1. Linux editor – use of vim

2.1.1. Basic concepts of vim
  • vimThere are many modes, currently we only need to master three, namelycommand mode (command mode), < a i=3>Insert mode and last line mode (last line mode), each mode The functions are divided as follows:

    • Normal/Normal/Command Mode(Normal mode)

      Control the movement of the screen cursor, delete characters, words or lines, move and copy a section and enter Insert mode, or go to last line mode

    • Insert mode(Insert mode)

      Only in Insert mode, text input can be done. Press the "ESC" key to return to the command line mode. This mode is the most frequently used editing mode by us later.

    • Last line mode(last line mode)

      Save or exit the file, you can also perform operations such as file replacement, string search, and line number listing. In command mode, shift+: can enter this mode. To see all your patterns: open vim and enter the bottom row of patterns directly :help vim-modes.

2.1.2. Basic operations of vim
  • Entervim, enter vim and file name at the system prompt, then enter the vim full-screen editing screen .

    vim test.c

    Here we notice that when enteringvim it is [NORMAL mode] (normal mode/command mode). If you need to enter information, you need to switch to [Insert mode] (INSERT mode).

  • [Normal Mode] Switch to [Insert Mode], first press esc in the upper left corner of the keyboard (just in case, just use esc without thinking). Now press any of the three letters on the keyboard:

    entera

    enteri

    entero

  • [Insert mode] switches to [Normal mode]

    Currently in [Insert Mode], you can only keep typing text. If you find that you have entered a wrong word and want to use the cursor keys to move back and delete the word, you can first press the "ESC" key to go to [Normal Mode] and then delete it. Word. Of course, you can also delete it directly.

  • [Normal Mode] Switch to [Last Line Mode]

    Enter "shift + ;", which actually means entering ":"

  • Exitvim and save the file. In [Normal Mode], click the ":" colon key to enter "Last line mode", for example:

    :w — save current file

    :wq — Save current file and exitvim

    :wq! — Save current file and force quitvim

    :q! — force quit without savingvim

2.1.3. vim normal mode command set
  • Move cursor

    • vimYou can directly use the cursor on the keyboard to move up, down, left, and right, but the formal vim is to use the lowercase English letter "h" (note: the leftmost of the four letters), " j" (smart memory: jump, jump down), "k" (smart memory: king, king, high above), "l" (smart memory: the rightmost of four letters), respectively control the left, down, and up of the cursor , move one space to the right
    • Press "G" (shift+g): move to the end of the article
    • Press " $ " (shift+4): Move to the "end of line" of the line where the cursor is located
    • Press "^" (shift+6): Move to the "beginning" of the line where the cursor is located
    • Press "w": the cursor jumps to the beginning of the next word
    • Press "e": the cursor jumps to the end of the next word
    • Press "b": the cursor returns to the beginning of the previous word
    • Press "#l": the cursor moves to the #th position of the line, such as: 5l,56l
    • Press [gg]: enter the beginning of the text
    • Press "ctrl" + "b": the screen moves "back" one page
    • Press "ctrl" + "f": the screen moves "forward" one page
    • Press "ctrl" + "u": the screen moves half a page "back"
    • Press "ctrl" + "d": the screen moves half a page "forward"
  • Delete text

    • "x": Each time you press it, delete a character at the cursor position.
    • "#x": For example, "6x" means to delete the 6 characters "behind (including yourself)" where the cursor is located
    • "X" (shift+x): Capital X, each time you press it, delete the character "before" the cursor position.
    • "#X": For example, "20X" means to delete the 20 characters "before" the cursor position.
    • "dd": delete the line where the cursor is (with cutting function), can be used with p
    • "#dd": Delete # lines starting from the line where the cursor is located
  • copy and paste

    • "yw": Copy the characters from the cursor to the end of the word into the buffer.

    • "#yw": Copy # words to the buffer

    • "yy": Copy the line where the cursor is to the buffer.

    • "#yy": For example, "6yy" means copying 6 lines of text "counting down" from the line where the cursor is located.

    • "p": Paste the characters in the buffer to the cursor position.

      Note: All copy commands related to "y" must be combined with "p" to complete the copy and paste function.

  • replace

    • "r": Replace the character where the cursor is.

    • "R" (shift+r): Replace the character where the cursor is until the "ESC" key is pressed.

  • Undo last operation

    • "u": If you execute a command by mistake, you can press "u" immediately to return to the previous operation. Press "u" multiple times to perform multiple replies

    • "ctrl + r" (note not shift+r): Undo recovery

  • jump to specified line

    • "ctrl" + "g" lists the line number of the line where the cursor is located.
    • "#G": For example, "12G" means moving the cursor to the beginning of line 12 of the article.
  • In vim, you can select multiple lines for comments through the following steps:

    1. Enter command line mode, pressctrl + v to enter visual block mode.
    2. Press j or k to select multiple lines that need to be commented.
    3. Press a capital letterI and then insert a comment character, for example//.
    4. Pressesc and all comments will be made.

    Canceling multi-line comments is a similar operation:

    1. Enter command line mode, pressctrl + v to enter visual block mode.
    2. Press lowercase letterslThe number of columns selected horizontally, for example, 2 columns need to be selected.
    3. Press j or k to select the comment symbol.
    4. Pressd to cancel all comments.
  • In vim, there are two shortcut methods for selecting multiple lines for indentation:

    method one:

    1. Enter command line mode, pressctrl + v to enter column editing mode.
    2. Pressshift + v to select the lines that need to be indented.
    3. Once selected, use `=" for indentation or "<" ">" for indentation.

    Method Two:

    1. Enter command line mode, pressctrl + v to enter column editing mode.
    2. Pressshift + v to select the lines that need to be indented.
    3. After is selected, use the shortcut key command(花键)+] to perform right indentation. Similarly, use the shortcut key command(花键)+[ to perform left indentation.

    The above are two methods of selecting multiple lines for indentation in vim.

2.1.4. Vim end line mode command set

Before using the last line mode, please remember to press the "ESC" key to make sure you are in the normal mode, and then press the ":" colon to enter the last line mode.

  • List line numbers

    • "set nu": After entering "set nu", the line number will be listed in front of each line in the file.

  • Jump to a certain line in the file

    • 「#」: The 「#」 sign represents a number. Enter a number after the colon and press the Enter key to jump to that line. For example, enter a number12. Press Enter again and it will jump to line 12 of the article.

  • Find characters

    • "/Keyword": Press the "/" key first, and then enter the characters you want to find. If the keyword you are looking for for the first time is not what you want, you can keep pressing "n" to find the key you want later. So far.

    • "?Keyword": Press the "?" key first, and then enter the characters you want to find. If the keyword you are looking for for the first time is not what you want, you can keep pressing "n" to search forward to find the key you want. So far.

      Question: / and ? Find the difference between and ? Experiment with the operation

      answer:/ Search from front to back,? Search from back to front

  • UsemanTempo

    In Vim, you can use the :!man command to view the man manual. For example:

    1. Open Vim.
    2. Enter command line mode (press Esc key).
    3. Enter :!man <command>, where <command> is the command you want to view the manual for.

    Example::!man ls

  • save document

    • "w": Enter the letter "w" in the colon to save the file.
  • Exit vim

    • 「q」: Press "q" to exit. If you cannot leavevim, you can force exit by following "q" with a "!"vim .
    • "wq": It is generally recommended to use it with "w" when leaving, so that the file can be saved when exiting.
  • multi-window mode

    Last line schematic importvs 文件, likevs code.c.

    If you want to switch the cursor to another file at this time, first esc, thenctrl+ww, so that the cursor will move to another file

2.2. Simple configuration of vim

  • Configuration file location

    • Under the directory /etc/, there is a file named vimrc. This is the public vim configuration file in the system and is valid for all users.

    • In each user's home directory, they can create their own private configuration file and name it: ".vimrc". For example, in the /root directory,

    • Usually a .vimrc file already exists. If it does not exist, create it.

    • Switch the user to become yourself and execute su, enter your main working directory, and execute cd ~

    • Open the .vimrc file in your own directory and execute vim .vimrc

  • Common configuration options for testing

    • Set syntax highlighting: syntax on
    • 显士行版: set nu
    • Set the number of spaces for indentation to 4: set shiftwidth=4

    After editing the following content in vim .vimrc, save and exit (input: wq in bottom line mode).


3. Linux compiler – gcc/g++ use

3.1. Background knowledge

  • Code running process:

    1. Preprocessing (for macro replacement)

    2. Compile (generate assembly)

    3. Assembly (generating machine-readable code)

    4. Link (generate executable file or library file)

3.2. How to complete gcc

Format:gcc [选项] 要编译的文件 [选项] [目标文件]

  • Preprocessing (for macro replacement)

    • Preprocessing functions mainly include macro definition, file inclusion, conditional compilation, comment removal, etc..

    • Preprocessing directives start with #Line of code.

    • Example:gcc –E test.c –o test.i

    • Option "-E",The function of this option is to make gcc stop the compilation process after preprocessing is completed.

    • The option "-o" refers to the target file, and the ".i" file is the preprocessed C original program.

  • Compile (generate assembly)

    • In this stage, gcc must first check the standardization of the code, whether there are grammatical errors, etc., to determine the actual work of the code. After the check is correct, gcc translates the code into assembly language.

    • Users can use the "-S" option to view,This option only compiles without assembling, and generates assembly code.

    • Example:gcc –S test.i –o test.s

  • Assembly (generating machine-readable code)

    • The assembly phase is to convert the ".s" file generated during the compilation phase into a target file

    • You can use the option "-c" here to see that the assembly code has been converted into ".o"binary object code

    • Example:gcc –c test.s –o test.o

  • Link (generate executable file or library file)

    • After successful compilation, it enters the linking stage and forms an executable file after linking.

    • Example: gcc test.o –o test

  • Run executable file

    • Example:./test

3.3. Function library

  • In our C program, the function implementation of "printf" is not defined, and the "stdio.h" included in the precompilation only has the declaration of the function, but does not define the implementation of the function. So, where is the implementation of " What about printf” function?
  • In fact, the system has implemented these functions into a library file named libc.so.6. When specifically specified, gcc will search in the system's default search path "/usr/lib", that is, link to the libc.so.6 library function, so that the function "printf" can be implemented, and this is The role of links.
  • Linux function libraries are divided into two types: static libraries and dynamic libraries.
  • The name of a static library (or static link library) is usually suffixed with .a. It is a collection of external functions and variables. During compilation, the compiler and linker will integrate the static library into the application and produce it into an object file and an executable file that can operate independently. This executable contains a complete copy of the library code. The advantage is that the compiled executable program does not require external function library support because all functions used have been compiled in. The disadvantage is that there will be multiple redundant copies when used multiple times.

  • The name of a dynamic library (or dynamic link library) usually ends with .so, which is not compiled into the target code during compilation. The corresponding function in the function library will be called only when the program executes the relevant function, so the executable file generated by the dynamic library is relatively small. Since the function library is not integrated into the program, but is dynamically applied for and called when the program is running, the corresponding library must be provided in the running environment of the program. Changes to the dynamic library do not affect the program, so it is more convenient to upgrade/update the dynamic library.

  • The binary program generated by gcc by default is dynamically linked. This can be verified through the file command.

  • In Linux systems, library files are usually stored in the /usr/lib or /lib directory.

  • Go back to the root directory/, enter cd lib64/, then ll, and you can see the files in this directory.


  • gcc option memory

    • ESc: Upper left corner of keyboard

    • iso:Image file


4. Linux project automated build tool-make/Makefile

4.1, make sum Makfile

make is a tool (command) forautomating project building, usually used to compile and link source code files to generate executable files or library. Makefile is the configuration file used by the make tool, it defines the dependencies and build rules between files in the project a>, you can ensure that components of your project are only rebuilt when needed, thereby improving development efficiency. make and . With Makefile

Here are the basic concepts about make and Makefile:

  1. make command: The make command is executed by the user and builds the project according to the rules defined in the Makefile file. By default, make will look for a file named Makefile or makefile in the current directory, but this can also be done by using or The a> file. -f option specifies the name of anotherMakefile

  2. Makefile file: Makefile file is a text file that contains a set of rules and goals. Each rule defines one or more target files, as well as the dependency files and build commands required to build those target files. Rules usually follow the following format:

    target: dependencies
        command
    
    • target: Indicates the target file that needs to be built.
    • dependencies: Indicates the dependency files required to build the target file.
    • command: Indicates the command to build the target file.

    For example:

    my_program: main.c utils.c
        gcc -o my_program main.c utils.c
    

    In this example, my_program is the target file, which depends on main.c and utils.c, and the build command is using gcc Compiles these source files to produce an executable file.

  3. Dependency: The dependency relationship in Makefile represents the relationship between the target file and the dependent file. If the dependent file changes, or the target file does not exist, make will execute the build command in the rule, to ensure that the target file is up to date< a i=5>.

    • The above file test , which depends on test.o
    • test.o , which depends on test.s
    • test.s , which depends on test.i
    • test.i , which depends on test.c

  4. Automated Build:make A major advantage of the tool is its ability to automatically detect which files need to be rebuilt to reduce unnecessary compilation and linking operate. It will only rebuild changed or missing files, not the entire project.

  5. Variables and functions:Makefile supports variables and functions, which can be used to simplify the definition of rules and improve maintainability. You can define variables in Makefile and then reference them in rules. For example:

    CC = gcc
    CFLAGS = -Wall -O2
    
    my_program: main.c utils.c
        $(CC) $(CFLAGS) -o my_program main.c utils.c
    

    In this example, CC and CFLAGS are variables that store the compiler and compilation options so that Makefile More flexibility.

make and Makefile are very useful tools in Unix/Linux development, they help automate and simplify the build process of the project. By defining clear rules and dependencies, the project's build process can be managed and maintained more efficiently.

4.2、make clean 和 .PHONY

make clean and .PHONY are two important concepts related to make and Makefile.

  1. make clean

    make clean is a common make command, usually used to clean the project directory and delete generated files and temporary files. In Makefile, you can define a pseudo target (phony target) named "clean" and list it in Select the files or directories that need to be deleted. This way, when make clean is run, make will perform the cleanup operation.

    Here is an example rule in Makefile:clean

    clean:
        rm -f *.o my_program
    

    In this example, clean is a pseudo target that has no actual file dependencies, but will be executed when make clean is run. files and executable filesrm -f *.o my_program command to delete all.omy_program

  2. .PHONY

    .PHONY is a special target used to tell make which targets are pseudo-targets (not representing actual files), to prevent make from misinterpreting these targets . Usually, pseudo-targets do not represent actual files in Makefile but are used to perform specific operations or tasks (such as clean data).

    By using .PHONY you can explicitly tell make which targets are pseudo-targets. For example:

    .PHONY: clean
    
    clean:
        rm -f *.o my_program
    

    In this example, .PHONY: clean means "clean" is a pseudo-goal. This helps avoid conflicts with actual files or directories of the same name and ensures that make clean is always executed clean rule.

    Since the previous make command has been compiled once, make will not be executed without modifying the file. If you want to execute it again, you can use this .PHONY (set each file as a pseudo target).

    This way you can execute the make command multiple times.

Pseudo objects have two functions:

  1. Causes the target object to be regenerated anyway

  2. It does not generate target files, but to execute some instructions

In summary, make clean is a common make command for cleaning project directories, while .PHONY is used to mark fake targets , to ensuremake handles these targets correctly. Used together, these two can help you better manage your project's build and cleanup operations.


5. Linux’s first small program - progress bar

5.1. The difference between \r (carriage return) and \n (line feed)

  • Carriage Enter: Carriage return character (ASCII code is 13, expressed as \r)Move the cursor to the beginning of the current line, allows you to overwrite already existing text on the same line. In Unix and Linux systems, carriage returns are generally not used to wrap text in text files.

  • Newline: Newline character (ASCII code is 10, represented as \n)Move cursor to next line, used to separate different lines of text. In Unix and Linux systems, lines of text files are usually separated by newlines.

5.2. Row buffer concept

Linux's line buffering is a data transfer mode that operates on a line-by-line basis when reading and writing text data. Specifically, the data will be divided into rows and will not be processed until the end of a row. This is usually used for standard input and standard output, meaning that the output of commands and programs entered by the user on the terminalwill not be processed until the end of a line. If you need to process data in real time, you can choose to disable row buffering so the data will be transferred faster (you can also use **fflush(stdout)**).

Disable row buffering: Sometimes, you may want to disable row buffering in order to process data in real time. You can change the buffering mode using the setbuf function or setvbuf function from the standard C library, or using the Unix system call setvbuf . For example, the following example disables buffering of standard output:

setbuf(stdout, NULL); // 禁用标准输出的缓冲
  • Look at the code below:
  #include <stdio.h>    
      
  int main(){
    
        
      printf("hhaaaaaahhhhhhaahah\r");                                          
      //fflush(stdout);    
    	sleep(3);    
      printf("\n");    
      return 0;                 
  }
  • Run result

  • 电影后:
  #include <stdio.h>    
      
  int main(){
    
        
      printf("hhaaaaaahhhhhhaahah\r");                                          
      fflush(stdout);    
    	sleep(3);    
      printf("\n");    
      return 0;                 
  }
  • Run result

5.3. Progress bar code

5.3.1. Simple progress bar code (printf)

  • main.ctext

    #include <stdio.h>    
    #include <unistd.h>    
    #include <string.h>    
    int main()    
    {
          
              
      	int i = 0;    
      	char bar[101];    
      	memset(bar, 0 ,sizeof(bar));    
      	const char *lable="|/-\\";    
      	while(i <= 100 ){
          
              
        	printf("[%-100s][%d%%][%c]\r", bar, i, lable[i%4]);    
        	fflush(stdout);    
        	bar[i++] = '#';    
        	usleep(100000);    
      	}
      	printf("\n");
      	return 0;                                                                                                              
    }
    
  • Run result

5.3.2. Progress bar code that simulates real situations

  • processbar.h Sentence:

    #include <stdio.h>                                                              
    #include <time.h>    
    #include <unistd.h>    
    #include <stdlib.h>    
        
    //函数指针    
    typedef void(*callback_t)(double);    
        
    //进度条    
    void process(double rt);
    
  • processbar.c Sentence:

    #include "processbar.h"    
        
    const char *lable="|/-\\";    
        
    void process(double rt){
          
              
        static int num = 0;    
        static char bar[101] = {
          
          0};    
        printf("[\033[0;32m%-100s\033[0m]][%5.1f%%][%c]\r", bar, rt, lable[num%4]);     ++num;
        fflush(stdout);
        bar[(int)rt] = '#';
        if((int)rt == 100) printf("\n");
    }
    
  • main.c text

    void downlode(callback_t cb) {
          
          
        srand(time(NULL) ^ 1023);
        long total = FILESIZE;
        while (total) {
          
          
            usleep(100000);//下载动作
            long one = rand() % (1024 * 1024 * 5);
            total -= one;
            if (total < 0) total = 0;
    
            //当前进度
            double rate = ((FILESIZE - total) * 1.0) * 100 / FILESIZE;
    //        printf("%.1f\n", rate);
            cb(rate);
        }
    }
    
    int main() {
          
          
        downlode(process);
        return 0;
    } 
    
  • Run result


6. Linux debugger-gdb use

6.1. Background

  • There are two ways to release a program, debug mode and release mode.

  • Binary programs produced by Linux gcc/g++ are in release mode by default.

  • To use gdb debugging, you must add the -g option when generating a binary program from source code.

6.2. Use

  • Exit: ctrl + d or quit

  • Test command:

    • r: run it

    • list/l line number: displays the code after the specified line (gdb automatically records the latest instruction)

    • b Line number/function name/file: line number: break point at the specified position of the heap

    • info b: View the breakpoints we hit

    • d breakpoint number: delete breakpoint

    • disable/enable breakpoint number: enable (disable/enable) breakpoint, note that the number here is the number displayed when info b

    • n: statement by statement – ​​F10

    • s: process by process – F11

    • p: Display the content and address of the variable

    • display variable name/address: often display the content or address of the variable

    • undisplay number: Undisplay the content or address of the variable. Note that here is the number. This number is the number displayed in the display.

    • c: Run from one breakpoint to the next (can be used for problem scope finding)

    • finish: Stop a function after running it (can be used to search for problem scope)

    • until: within a range, run directly to the specified line (can be used for problem range search), cannot skip function calls, generally used to skip loops

    • bt: View call stack

    • set var name=value: Modify the content of a variable (no need to change the code, can be used for multi-branch testing)

  • MakefileText content:

    test_gdb:test_gdb.c                                                             
        gcc -o $@ $^ -g    
        
    .PHONY:clean    
    clean:    
        rm -f test_gdb
    
  • test_gdb.cText content:

    #include <stdio.h>    
        
    int Sum(int n){
          
              
        int i = 1;    
        int sum = 0;    
        for(; i<=n; ++i){
          
              
            sum += i;    
        }    
        return sum;                                                                 
    }    
        
    int main(){
          
              
        
        int result = Sum(100);    
        printf("result = %d\n",result);    
        
        return 0;    
    }
    
  • Test debugging function




Well, that’s it for Linux development tools. If you are also interested in Linux and C++, you can check out my homepage. Below is my github homepage, which records my learning code and solutions to some problems of leetcode. If you are interested, you can take a look.

Xpccccc’s github homepage

Guess you like

Origin blog.csdn.net/qq_44121078/article/details/134572384