当前位置:网站首页>Fundamentals of C language
Fundamentals of C language
2022-07-05 07:54:00 【Soy sauce;】
One . Preprocessing
1.c Code compilation process
1. Precompiling of header files , Preprocessing
When the compiler compiles the source code , The header file will be compiled first , Make sure that each header file is compiled only once .
In the pretreatment stage , Compiler will c All the contents of the header file referenced in the file are written to c In file .
2. Lexical and grammatical analysis ( Error checking )
3. compile ( Assembly code ,.obj file )
.h Put function declaration , Will go to the current folder in the project .c Find out the equivalent function definition
It's converted into a sink code , This kind of file is called the target file . The suffix is .obj.
4. link ( Binary machine code ,.exe file )
Converting assembly code into machine code , Generate executable files .
During the compilation process ,.h Everything in the file will be written to the .c In file , And all under the current folder .c The document is in a common main Function as the entry to the executable program .
stay .h The function implementation written in the file can still be compiled and executed normally , Equivalent to all of .h The content of the book was written in the end main.c In file . But for the sake of logic 、 Ease of maintenance and some other purposes , Generally in .h Write the function declaration in the file , stay .c The realization of writing function in file . Generally, macro constants , Macro functions , Structure , Template declaration , data type , Declare external variables , Declare function declaration . Put header file (.h)
2. precompile , What is the first thing to do in the compilation process ?
Or what is preprocessed
answer : compile # Instructions beginning with words , Such as Copy #include Included header file code ,#define Replacement of macro definitions , Conditional compilation ifndef
3. When to precompile ?
answer :
① Large code that is often used but not often changed .
② The program consists of several modules , All modules use a standard set of include files and the same compilation options , Precompile all include files into one “ Precompiled translation head ”.
4. c In language # And ## The difference and function of
answer :# : Change the macro parameter into a string ;
## : Connect the two macro parameters together ( Only two. )
Example
#include <stdio.h>
#include <stdlib.h>
#define ONE 1 //1. The most common is # Parameters will not be replaced , Only replace the corresponding characters ;
#define toString(str) #str //2. Macro parameter to string
#define hehe(x,y) x##y // Macro parameters to connect
int main()
{
printf("%d\n",ONE); //# Parameters will not be replaced , Only replace the corresponding characters ;
printf(toString(123456)); // Output string "123456"
printf("\n %d \n",hehe(1,2)); // Output int 12
char string[]="hello world!";
puts(hehe(str,ing));
printf("%s\n",hehe(str,ing));
system("pause");
return 0;
}
Output results :
1
123456
12
hello world!
hello world!
**3. How to avoid repeated inclusion of header files when calling ? **
answer : resolvent : application #ifndef #define #endif
/* How to explain !: // The first time did not define perform include, The second time has #define Unqualified ( On the condition that notdefine, And already define 了 ) So don't execute include*/
#ifndef _STM32F10X_GPIO_H
#define _STM32F10X_GPIO_H
#include "stm32f10x.h" // Here is the content of the header file
#endif
Two . keyword
1. static The role of keywords ?
answer :static The main function is hide , Second, because static Variable storage Put it in the static storage area , It has persistence and the default value is 0
① Hiding effect , Variables and functions with the same name can be defined in different files .
② For variables , Keep variables persistent , The variables in the static data area will be completed just when the program is running initialization , It's also the only initialization ; Stored in the static data area .
There are only two variables in static storage ( whole Local variables and static Static variables ).
③ Default initialization is 0x00, The same properties as global variables , Reduce the programmer's workload .
2. static What's the difference between global variables and ordinary global variables ?
Global variables ( External variables ) Before the description of static It's a static global variable .
Global variables themselves are static storage , Static global variables are also static storage . There is no difference between the two in the way of storage .
The difference between the two is that the scope of non static global variables is the whole source program , When a source program consists of multiple source files ,** Non static global variables are valid in all source files . Static global variables limit their scope , That is, it is only valid in the source file where the variable is defined , It cannot be used in other source files of the same source program .** Because the scope of static global variables is limited to one source file , Can only be used for functions within the source file , So you can avoid causing errors in other source files .
static Can only be used when calling your own function .
static Global variables are initialized only once , Prevent references in other file units ;
3. const The role of keywords
answer :① Limiting variables cannot be modified , Constants must be initialized at the same time as they are defined .
②const Use with pointer , const int *p1; int const *p2; int *const p3; In three cases , The third kind of pointer is read-only ,p3 The value of itself cannot be modified ; The first two cases , The data pointed to by the pointer is read-only ,p1,p2 The value of can be modified , But the number pointed It cannot be modified .
③const Use with function parameters Use const To define variables individually, you can use #define Command substitution ,const Usually placed in function parameters . If the parameter is a pointer , To prevent modifying the data pointed to by the pointer inside the function, you can use const To limit .
4. volatile The role of keywords ?
Introduction to compiler optimization : Memory access speed is far less than cpu Speed of processing , To improve performance , Introduce cache from hardware cache, Speed up access to memory .
The methods of compiling optimization are : Cache memory variables into registers ; Adjust the order of instructions to make full use of CPU finger Make the assembly line . Do not access memory , Access registers , Save time .
answer : Because accessing registers is much faster than accessing memory cells , The editor will optimize to reduce access . When using volatile When declaring function variables , The system always rereads data from its memory . Encountered the variable declared by this keyword , The compiler no longer optimizes the code that accesses the variable , Thus, it is suggested that For stable access to special addresses ;( Prevent code from being optimized ) If not used valatile, The compiler will optimize the declared statement , To avoid mistakes .
5. extern The role of keywords ?
answer : What is in the function is a local variable Variables defined outside the function are global variables , Static storage , The life cycle is the whole program , The valid range is Define the position of variables from the beginning to the end of this source file .
a. If you want to reference this global variable before definition , You should add extern As “ Declaration of external variables ”.
b. If a project with multiple source files wants to reference an external variable of a source file, it is only allowed to add extern Keyword to declare , However, you can modify the value of its variables in the referenced module , Use with caution .
c. extern “C”: C++ Code calls C The language code . stay C++ Used in the header file of .
6. sizeof The role of keywords ?( a key )
answer :sizeof stay Compile phase processing , The function is to get an object ( Data type or data object ) Of length ( That is, the size of memory , With 1 Bytes are units ).
① Pointer can be regarded as a kind of variable ,32 Bit operating system sizeof The hands are 4, Example : int *p; sizeof§ =4; sizeof(*p) = sizeof(int )=4;
② For static arrays ,sizeof You can directly calculate the size of the array , example : int a[10]; char b[ ]= “hello”; Sizeof (a) = 4 * 10 =40; Sizeof (b) = 6; ( When calculating the length of a string, add the string terminator /0)
③ When an array is used as a function parameter , Array name as pointer Use , example : Void fun (char p[ ]) { Sizeof § ; // The result is 4 }
7. sizeof And stelrn The difference between :
*sizeof It's the operator , strlen For the function ;
sizeof You can use type as a parameter , Such as int char; Add \0
strlen Only use char( Generally used for Strings ) Make parameters with \0 For the end
*sizeof For array , No degradation , Pass to strlen The array will be degenerated into an orange pointer , The calculated size is not calculated \0
3、 ... and . Structure
1. Assignment method of structure :
① initialization : Such as : Struct st{ Char a; Int b; }x={ ‘A’, 1 };
② Assign values by field after defining variables , Such as : Struct st{ Char a; Int b; }; Struct st x; X.a = ‘A’; X.b = 1;
③ Assignment of structure variables , Such as : Struct st { Char a; Int b; } ; Struct st x,y; X.a= ‘A’; X.b=1; Y=x;
2. The structural domain
Bit field type : char, short,int Can be carried (signed perhaps unsigned)
Definition of bit field : struct st{
Unsigned char a:7; // Field a Take up one byte 7bit( position )
Unsigned char b:2; // Field b Take up one byte 2ibt( position )
Unsigned char c:7; }s1;
Benefits of bit fields :
① You don't need full bytes , Save storage space , Simple processing ;
② It is convenient to decompose a variable by bit field ; But it is not conducive to the transplantation of the program !!
3. Calculate the size of a structure ,sizeof(struct s1)
① The concept of structure offset : The offset in the structure refers to the distance between the actual address of a member and the first address of the structure .
② Calculation method of structure size : The structure experience involves byte alignment ,( The purpose is to make the computer read quickly , Exchange space for speed ), That is, the size of the last member + The offset of the last member + Number of filled sections at the end .
③ In structure offset rules
First step : The offset of each member must be an integer multiple of the memory size occupied by the current member , If not An integral multiple , The compiler will fill in bytes before .
The second step : When all member sizes are calculated , The compiler will determine whether the current structure size is the widest An integer multiple of the size of a structure member , If it's not an integer multiple , The compiler fills in bytes .
example :Struct s1{
The size of the member Offset of member
int a; 4 0
char b; 1 4
int c; 4 5+3( Fill bytes )
long d; 8 12+4( Fill bytes )
char e; 1 24
}
Sizeof(s1)=24+1+7( Fill bytes ) (24+1 It's the total size , Want to be with 8 The comparison is an integer multiple )
4. Structure member array size
①Struct st { Int a; Int b; Char c [ 0 ]; }st_t; sizeof(st_t) = 8
②Struct book {
Char name[5];
Float price;
}book[2];
sizeof[book]=24; although book It also refers to the first address, but it refers to a whole, so 24
sizeof[&book[0]]=4;// The memory space of a single first address is always 4, Regardless of data type , Because there are four cells in the memory
Sizeof( book[1] ) = 12; A single calculation is 12
Sizeof (book[2]) = 12;
First step : The elements whose structure members account for a large number of bytes are sizeof ( float ) = 4; Then use 4 To allocate other member ;
The second step : The array is more than four bytes , Continue with line break , Which byte left is not enough float Type data use , Then line break
Four . Interviews are common
1. The difference between reference and pointer :
① References must be initialized , Pointers do not have to be initialized
② The reference cannot be changed after initialization , But the pointer can change the object it refers to
③ There is no reference to null value , But there are null pointers
2. .h Header file , ifndef /define /endif The role of
① Prevent the header file from being called repeatedly
3. include<file.h> and includ”file.h” The difference between ?
① The former looks for files from the library functions provided by the compiler , from Standard library path Start searching for files
② The latter is to find files from customized files , Can't find. Go to the library function to find the file
4. The difference between global and local variables ?
① Global variables -> Stored in Static data area , Occupy a static storage unit
② local variable -> Stored in In the stack , Only when the function is called does the allocation of storage units begin a key
5. What are the causes of stack overflow ?
① Function call level too deep , When a function is called recursively , The system should keep the line when the function is called in the stack Process and generated variables , Recursive call too deep , Will cause stack overflow , This is recursive and cannot be returned .
② The dynamic application space is not released after use . because C There is no automatic garbage collection mechanism in the language , because This requires programmers to actively release the dynamic address space that is no longer used .
③ Array access out of bounds ,C The language does not provide array subscript out of bounds checking , If the array appears in the program Mark access is out of array range , There may be memory access errors during operation .
④ Pointer illegal access , The pointer holds an illegal address , Access the address pointed to through such a pointer Memory access error will occur .
6. The difference between queues and stacks
The same thing : Stack and queue are restricted to insert and delete only in the table “ Endpoint ” Linear table for Difference : Stack elements must “ First in, then out ”, queue Element must “ fifo ”
7. Can a local variable have the same name as a global variable ?
can , Local variables will mask Global variables , To use global variables , Need to use ”::”;
Local variables can have the same name as global variables , When you refer to this variable within a function , You use local variables with the same name , Instead of using global variables
8. How to reference a defined global variable ?
① use extern Keyword mode
② Use reference header file , The premise is that there can only be one of them C The initial value of this variable is assigned in the file , At this time There will be no mistake .
9. Can a global variable be defined in multiple .c The file contains the header file , Why? ?
Sure , In different C In the document, use static Declared global variables , Variable names may be the same , however Their respective C The scope of the global variable in the file is the file , So don't interfere with each other .
10.Do…while and while …do The difference between ?
①do …while : Cycle once and then judge
②while …do : Judge first and then cycle
11.static The key word in Global variables 、 local variable 、 Difference of function ?
① Global variables +static : Change scope , change ( Limit ) Its scope of use . Initialize only once , Prevent references in other file units . The scope of a global variable is the entire Source program , It is valid in each source file , And the scope of the global variable after adding static Limited to In a source file .
② local variable +static : Change how it is stored , That is, it changes its survival time .
③ Ordinary function +static : Different scopes , Only in this document . Functions used only in the current source file should be described as internal functions (static), Internal functions should Describe and define in the current source file , For functions that can be used outside of the current source file , It should be in a The header file says , The source file to use these functions should contain this header file .
12. Program memory allocation ( Regular examination )
Preface :c Language program .c The file is compiled and connected to form a compilation 、 Binary image text formed after linking The piece is made up of Pile up ,、 Stack 、 Data segment ( Read only data segment , Uninitialized data segment BSS, Initialized data segment three part )、 Code segment composition
① The stack area (stack): Managed by the compiler , Automatic allocation and release , What is stored is that the function has been called Various parameters in the process , local variable , The return value and the return place of the function site .
② Heap area (heap) : It is used for dynamic application, allocation and release of space ,malloc and free, The programmer The space requested should be released after use , The program automatically retracts .
③ overall situation ( static state ) Storage area : It is divided into DATA( Already initialized ),BSS( uninitialized ) paragraph ,DATA The segment stores global variables and static variables ; BSS( uninitialized ) Store uninitialized global variables and Static variables . Automatically release after the program runs , among BSS( All uninitialized areas ) The system will automatically Zero clearing .
④ Text constant area : Store constant string , Released by the system at the end of the program .
⑤ Program code snippet : Store the binary code of the program .
13. explain ” Pile up ” and ” Stack ” The difference between :
notes : When asked this question, you can elaborate from these aspects
① Application method
② System response after application
③ Request memory size limit
④ Application efficiency
⑤ Store content
⑥ Distribution method
① Application method
: Strack( Stack ): Released by the compiler's own allocation , Stores the parameter values of the function , Local variables, etc . Heap( Pile up ): Programmers apply for , And name the size –>malloc function .
② System response after application Strack( Stack ): As long as there is space left in the stack > Space requested , Will provide . Heap( Pile up ): The operating system has a linked list of free memory : Received the application -> Traversing the linked list -> seek -> Heap of application space node
③ Request memory size limit Strack( Stack ): The result of extending data to low addresses , Continuous memory area , Stack Get less space . Heap( Pile up ): Extended to high address , Discontinuous memory area ; The traversal direction of the linked list is ( Low address -> High address ). Stack to obtain flexible space , There's a lot of space .
④ Application efficiency Strack( Stack ): The system is freely distributed , Fast . Heap( Pile up ): Slow speed , It is easy to generate memory fragmentation .
⑤ Store content Strack( Stack ): First into the stack : The address of the next instruction in the main function --> The parameters of the function , Parameters from right to left Into the stack .–> A local variable of a function ( Static variables are not stacked ). After call , In reverse order , Local variables first out of stack . Heap( Pile up ): The programmer arranges it himself
⑥ Distribution method Strack( Stack ): Stack There are two ways of distribution , Static and dynamic allocation . Static allocation is done by the compiler , For example, Bureau Allocation of partial variables , Dynamic allocation is made by alloca Function to allocate , But the dynamic allocation of stacks is different from that of heaps , Stack dynamics Memory is released by the compiler , No need to do it by hand . Heap( Pile up ): The heap is all dynamically allocated , No statically allocated heap .
- The difference between a structure and a consortium :
**① Structures and consortia :** Are composed of members of different data types , But at the same time , The consortium has only stored one Selected members ( All members share one address ); And structure members exist ( Different members have different storage addresses ). Example : * In the consortium abc in , Shaping quantity i And character m Share a memory location . * When a consortium is described , The compiler automatically generates a variable , Its length is the largest variable length in the consortium
② Different members of the consortium are assigned , Will override... For other members , The value of the original member will not exist . The assignment of different members of the structure does not affect each other
边栏推荐
- Global and Chinese markets for anesthesia, breathing and sleep apnea devices 2022-2028: Research Report on technology, participants, trends, market size and share
- How to migrate the device data accessed by the RTSP of the easycvr platform to easynvr?
- Software designer: 03 database system
- Global and Chinese market of blackbody calibration source 2022-2028: Research Report on technology, participants, trends, market size and share
- Use of orbbec Astra depth camera of OBI Zhongguang in ROS melody
- STM32 knowledge points
- Openxlsx field reading problem
- . Net service governance flow limiting middleware -fireflysoft RateLimit
- 万字详解八大排序 必读(代码+动图演示)
- Programming knowledge -- assembly knowledge
猜你喜欢
Can't find real-time chat software? Recommend to you what e-commerce enterprises are using!
Opendrive ramp
Significance and requirements of semiconductor particle control
Mlperf training v2.0 list released, with the same GPU configuration, the performance of Baidu PaddlePaddle ranks first in the world
Train your dataset with yolov4
[untitled] record the visual shock of the Winter Olympics and the introduction of the display screen
Numpy——1. Creation of array
Altium designer learning (I)
What is Bezier curve? How to draw third-order Bezier curve with canvas?
LED display equipment records of the opening ceremony of the Beijing Winter Olympics
随机推荐
Pointnet++ classification practice
Extended application of single chip microcomputer-06 independent key
Day08 ternary operator extension operator character connector symbol priority
Detailed explanation of pragma usage
Global and Chinese market of plastic recycling machines 2022-2028: Research Report on technology, participants, trends, market size and share
Query the table name used by kettle in Oracle
STM32 knowledge points
Define in and define out
Application of ultra pure water particle counter in electronic semiconductors
Cygwin installation
Global and Chinese market of urban rail connectors 2022-2028: Research Report on technology, participants, trends, market size and share
Count and sort the occurrence times of specific fields through SQL statements
Opendrive arc drawing script
STM32 learning method
Apple animation optimization
Oracle-触发器和程序包
Ads usage skills
Leetcode solution - number of islands
GPIO circuit principle of stm32
UEFI development learning 6 - creation of protocol