<>1. Write in front

Today is the first day of the lunar new year , First of all, I wish you a happy new year , Have nothing to do , It's nice to go home on holiday. I brought a book 《C Programming language 》 Second Edition , So I plan to finish reading the book during this holiday , study C Before language , We need some pre knowledge , for example :GCC,GDB,CMake. So I use today's time , Let's learn some of these things .

<>2.GCC compiler

<>2.1 Compilation process

preparation , Let's create one first main.c file , The specific contents are as follows :

# -E Option instructs the compiler to preprocess only the input file g++ -E main.c -o main.i //.i file
Generated after running the command main.i The contents of the document are as follows :

Can be found , Import many external files .

# -S Compilation options tell gcc In for C Stop compiling after the code generates the assembly language file # gcc The default extension of the generated assembly language file is .s gcc -S main.i
-o main.s
Generated by running commands main.s The contents of the document are as follows :

The corresponding assembly file has been generated here .

# -c Option tell gcc Only compile the source code into the object code of machine language # by default gcc The created object code file has a .o Extension of . g++ -c main.s
-o main.o
Generated by running commands main.o The contents of the document are as follows :

At this time, the generated file is already machine language .

# -o Compile option to use the specified file name for the executable to be generated gcc test.o -o test
The result of running the generated file is as follows :

You can see that our final file has been generated , At the same time, the file has been run .

<>2.2 gcc Important compilation parameters

-g Compile executable file with debugging information
# -g Option tell GCC Generation can be GNU debugger GDB Debugging information used , To debug the program . # Generate executable file with debugging information test gcc -g main.c
-o gmain

It can be found that the generated file with debugging information is larger than the file without debugging information .

-O[n] Optimize source code
## So called optimization , For example, omit variables that have never been used in the code , Directly replace the constant expression with the result value, and so on , These operations reduce the amount of code contained in the target file , Improve the running efficiency of the final generated executable file .
# -O Option tell g++ Basic optimization of source code . In most cases, these optimizations will make the program execute faster . -O2 Option tell gcc Generate code as small and as fast as possible .
as -O2,-O3,-On(n Chang Wei 0–3) # -O At the same time, reduce the length and execution time of the code , The effect is equivalent to -O1 # -O0 Indicates no optimization # -O1 Default optimization #
-O2 In addition to completion -O1 Beyond the optimization of , Some additional adjustments were also made , Such as command adjustment, etc . # -O3 It includes loop expansion and other optimization work related to processing characteristics . #
Option will make compilation faster than using -O Time slow , But usually the resulting code executes faster . # use -O2 Optimize source code , And output the executable file gcc -O2 test.c #
include <stdio.h> int main() { unsigned long int counter; unsigned long int
result; unsigned long int temp; unsigned int five; int i; for (counter = 0;
counter< 2009 * 2009 * 100 / 4 + 2010; counter += (10 - 6) / 4) { temp = counter
/ 1979; for (i = 0; i < 20; i++) { five = 200 * 200 / 8000; result = counter; }
} printf("result:%lu",result); return 0; }

A lot of junk code above , We can try this order ,gcc How much can we optimize . Compile and run in two ways respectively , The details are as follows , among v1 No optimization is used , then v2 The corresponding optimization method is adopted

Can be found , The running time of our optimized program is much less than that of the non optimized program .

-l and -L Specify library file | Specify library file path
# -l parameter ( a lowercase letter ) It is used to specify the library to which the program will link ,-l The parameter is followed by the library name #
stay /lib and /usr/lib and /usr/local/lib The library in the library can be used directly -l Parameters can be linked # link glog library gcc -lglog test.c #
If the library file is not in the above three directories , Need to use -L parameter ( Capitalize ) Specify the directory where the library file is located # -L The parameter is followed by the directory name where the library file is located #
link mytest library ,libmytest.so stay /home/bing/mytestlibfolder Under the directory gcc
-L/home/king/mytestlibfolder -lmytest test.c
-I Specify header file search directory
# -I # /usr/include Directories are generally not specified ,gcc Know where to look , but
Yes, if the header file is not present /usr/icnclude We'll use it in the -I Parameter specifies , For example, the header file is placed in /myinclude In the catalogue , Then compile the command line with I/myinclude
Parameters , If you don't, you'll get one ”xxxx.h: No such file or directory” Error of .-I Parameters can be relative paths , For example, the header file is currently
catalogue , Can use -I. To specify . We mentioned above –cflags Parameters are used to generate -I Parametric . gcc -I/myinclude test.c
-Wall Print warning message
# Print out gcc Warning information provided gcc -Wall test.c
-w Warning message off
# Turn off all warning messages gcc -w test.c
-std=c99 Set compilation criteria
# use c99 Standard compilation test.c gcc -std=c99 test.c
-o Specify the output file name
# Specifies the name of the file to be generated # Specifies that the output executable is named test gcc test.c -o test
-D Ding Yihong
# in use gcc/g++ Define macros when compiling # Common scenes : # -DDEBUG
definition DEBUG macro , There may be in the file DEBUG Information about the macro section , Use one DDEBUG To select on or off DEBUG
Sample code
// -Dname Ding Yihong name, The default definition content is string “1” #include <stdio.h> int main() { #ifdef DEBUG
printf("DEBUG LOG\n"); #endif printf("in\n"); } // 1. At compile time , use gcc -DDEBUG
main.cpp // 2. The seventh line of code can be executed
<>3.GDB debugger

<>3.1 preface

* GDB(GNU Debugger) Is a tool for debugging C/C++ Powerful debugger for programs , yes Linux system development C/C++ Most commonly used debugger
* Programmers can use GDB To track errors in the program , Thus reducing the workload of programmers .
* Linux development C/C++ Be familiar with GDB
* VSCode By calling GDB Debugger to implement C/C++ Of commissioning work ;
<>3.2 major function

* Set breakpoint ( Breakpoints can be conditional expressions )
* Causes the program to pause execution on the specified line of code , Easy to observe
* Single step program , Easy to debug
* View the change of variable value in the program
* Dynamically change the execution environment of the program
* Analyze the results of the crash program core file
<>3.3 Common debugging command parameters
## The following commands are simplified in parentheses , such as run(r), Direct input command r It's an order run $(gdb)help(h) #
View command help , Specific command query gdb Medium input help + command $(gdb)run(r) #
Restart running the file (run-text: Load text file ,run-bin: Load binary ) $(gdb)start # Single step execution , Run program , Stop at the first line to execute the statement $(
gdb)list(l) # View original code (list-n, From the first n Line start viewing code .list+ Function name : View specific functions ) $(gdb)set # Set the value of the variable $(gdb
)next(n) # Single step debugging ( Process by process , Function direct execution ) $(gdb)step(s) # Single step debugging ( Sentence by sentence : Jump into custom function internal execution ) $(gdb)
backtrace(bt) # View the stack frame and hierarchy of function calls $(gdb)frame(f) # Switch stack frame of function $(gdb)info(i) #
View the value of the local variable inside the function $(gdb)finish # End current function , Return to function call point $(gdb)continue(c) # Continue running $(gdb)
print(p) # Print value and address $(gdb)quit(q) # sign out gdb $(gdb)break+num(b) # In the first num Line set breakpoint $(gdb)
info breakpoints# View all currently set breakpoints $(gdb)delete breakpoints num(d) # Delete paragraph num Breakpoints $(gdb)
display# Track and view specific variable values $(gdb)undisplay # Cancel tracking observation variables $(gdb)watch # When the variable of the set observation point is modified , Print display
$(gdb)i watch # Show observation points $(gdb)enable breakpoints # Enable breakpoints $(gdb)disable breakpoints
# Disable breakpoints $(gdb)x # view memory x/20xw display 20 Units ,16 Base system ,4 Bytes per unit $(gdb)run argv[1] argv[2] #
Command line parameter passing during debugging $(gdb)set follow-fork-mode child#Makefile project management : Choose to track parent-child processes (fork())

* When compiling the program, you need to add -g, Then you can use it gdb Commissioning :gcc -g main.c -o main
* enter key : Repeat the previous command

<>4.1 preface

* CMake Is a cross platform installation and compilation tool , You can use simple statements to describe the installation of all platforms ( Compilation process ).
* CMake It can be said that it has become the majority C++ Standard configuration of open source projects
<>4.2 Introduction to grammatical features

* Basic syntax format : instructions ( parameter 1 parameter 2…)
* Parameters are enclosed in parentheses
* Parameters are separated by spaces or semicolons
* Instructions are case independent , Parameters and variables are case dependent set(HELLO hello.c) add_executable(hello main.c
hello.c) ADD_EXECUTABLE(hello main.c ${HELLO})
* ** Variable use ${} Method value , But in IF Variable names are used directly in control statements **
<>4.4 Important instructions

cmake_minimum_required - appoint CMake Minimum version requirements for

grammar : cmake_minimum_required(VERSION versionNumber [FATAL_ERROR])
# CMake The minimum version requirement is 2.8.3 cmake_minimum_required(VERSION 2.8.3)
project - Define project name , And the language supported by the project can be specified

grammar : project(projectname [CXX] [C] [Java])
# Specify the project name as HELLOWORLD project(HELLOWORLD)
set - Explicitly define variables

# Specify the project name as HELLOWORLD project(HELLOWORLD)
include_directories - Add multiple specific header file search paths to the project —> Equivalent to specified g++ Compiler -I parameter

grammar : include_directories([AFTER|BEFORE] [SYSTEM] dir1 dir2 …)
# take /usr/include/myincludefolder and ./include Add to header file search path
include_directories(/usr/include/myincludefolder ./include)
link_directories - Add multiple specific library file search paths to the project —> Equivalent to specified g++ Compiler -L parameter

grammar : link_directories(dir1 dir2 …)
# take /usr/lib/mylibfolder and ./lib Add to library file search path
link_directories(/usr/lib/mylibfolder ./lib)
add_library - Generate library file

grammar : add_library(libname [SHARED|STATIC|MODULE] [EXCLUDE_FROM_ALL] source1
source2 … sourceN)
# Pass variable SRC generate libhello.so Shared library add_library(hello SHARED ${SRC})
add_compile_options - Add compilation parameters

grammar :add_compile_options()
# Add compilation parameters -Wall -std=c99 -O2 add_compile_options(-Wall -std=c99 -O2)
add_executable - Generate executable

grammar :add_executable(exename source1 source2 … sourceN)
# compile main.cpp Generate executable main add_executable(main main.c)
target_link_libraries - by target Add shared libraries that need to be linked —> Same as specified g++ compiler -l parameter

grammar : target_link_libraries(target library1 library2…)
# take hello Dynamic library files are linked to executable files main target_link_libraries(main hello)
add_subdirectory - Add a subdirectory for storing source files to the current project , Intermediate binary and target binary can be specified Storage location

grammar : add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])
# add to src Subdirectory ,src One of them is required CMakeLists.txt add_subdirectory(src)
aux_source_directory - Find all source code files in a directory and store the list in a variable , This finger Temporary is used to automatically build the list of source files

grammar : aux_source_directory(dir VARIABLE)
# definition SRC variable , Its value is all source code files in the current directory aux_source_directory(. SRC) #
compile SRC The source code file represented by the variable , generate main Executable file add_executable(main ${SRC})
<>4.5CMake Common variables

CMAKE_C_FLAGS gcc Compile options

CMAKE_CXX_FLAGS g++ Compile options
# stay CMAKE_CXX_FLAGS Append after compile option -std=c++11 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}
CMAKE_BUILD_TYPE Compile type (Debug, Release)
# Set compilation type to debug, Selection is required during debugging debug set(CMAKE_BUILD_TYPE Debug) #
Set compilation type to release, You need to select when publishing release set(CMAKE_BUILD_TYPE Release)
1. The three variables refer to the same content . 2. If it is in source build, It refers to the top-level directory of the project . 3. If it is out-of-source
compile , It refers to the directory where the project compilation takes place . 4. PROJECT_BINARY_DIR It is slightly different from other instructions , But now , You can understand that they are consistent .
1. The three variables refer to the same content , No matter what compilation method is adopted , They are all top-level directories of the project . 2. That is, in in source build Time , He and
CMAKE_BINARY_DIR Equivariant consistency . 3. PROJECT_SOURCE_DIR It is slightly different from other instructions , Now? , You can understand that they are consistent .
CMAKE_C_COMPILER: appoint C compiler

CMAKE_CXX_COMPILER: appoint C++ compiler

EXECUTABLE_OUTPUT_PATH: Storage path of executable output

LIBRARY_OUTPUT_PATH: Storage path of library file output

<>6.6CMake Compile project

CMake directory structure : One exists in the project home directory CMakeLists.txt file

There are two ways to set Compilation Rules :

* Subfolders containing source files CMakeLists.txt file , Home directory CMakeLists.txt adopt add_subdirectory Just add a subdirectory ;
* The subfolder containing the source file does not contain CMakeLists.txt file , The subdirectory Compilation Rules are reflected in the main directory CMakeLists.txt in ;
<>6.6.1 Compilation process

stay linux Use under the platform CMake structure C/C++ The process of the project is as follows: :

* Manual writing CMakeLists.txt.
* Execute command cmake PATH generate Makefile ( PATH It's the top floor CMakeLists.txt Directory of ).
* Execute command make Compile .
<>6.6.2 Two construction methods

Internal construction (in-source build): Not recommended

Internal build will produce a lot of intermediate files in the same level directory , These intermediate documents are not what we need in the end , And engineering sources Documents can look disorganized when put together .
## Internal construction # Under current directory , Compiling this directory CMakeLists.txt, generate Makefile And other documents cmake . #
implement make command , generate target make
External construction (out-of-source build): Recommended use

Put the compiled output file and the source file in different directories
## External construction # 1. In the current directory , establish build folder mkdir build # 2. Enter into build folder cd build # 3.
Compilation of parent directory CMakeLists.txt, generate Makefile And other documents cmake .. # 4. implement make command , generate target make
<>5. Write at the end

This blog is about C Some things you need to prepare for language entry , I can really start watching it later 《C Programming language 》

©2019-2020 Toolsou All rights reserved,
C++ of string of compare usage Python Study notes ( one )evo Tool usage problems ——Degenerate covariance rank, Umeyama alignment is not possibleRISC-V_GD32VF103-TIMER0 timer interrupt java Array subscript variable _Java Basic grammar : array be based on stm32 Control four-wheel trolley motor drive ( one ) be based on redis Design of liking function Software engineering career planning mysql Query random data by conditions _MySQL Random query of several qualified records centos7 install RabbitMq