Header file and link of C notes (1)

Source: Internet
Author: User

Header file and link of C notes (1)

 

Although I have been using the # include command to include the header file, I don't quite understand the principle of the header file. I studied it today.

 

 

First of all, in a large project, it is not enough to have only one source file. The huge amount of code needs to be put in several files separately. Of course, the main purpose of separate storage is to facilitate modularization. We store the code in different files according to different functions or functions. When one of the functions is changed, we only need to re-compile the relevant files, instead of compiling all the source files of the entire project.

However, this raises the question: can a variable or function defined in a file be used in another file? Or will variables with the same name in two files cause conflicts?

To answer this question, you must first understand how the C language source code generates executable code step by step. Let's first look at the situation where there is only one source file:

First, replace the macro commands in the file with the pre-processor;

Then, the compilation code is generated by the compiler;

The next step is the assembler, which generates the binary target Code. However, the target code still cannot be executed, and it still lacks the startup code (interface between the program and the operating system) and library code (such as the entity code of the printf function );

Finally, the Code is linked through the linker to generate the final executable code.

 

Since we mentioned the compilation, we have to introduce the c language compiler gcc. If we have written a source file first. c, the gcc command parameters are as follows:

Pre-compile: gcc-E first. c-o first_1.c (Note: The-o option is used to specify the file name of the generated result)

Assembly: gcc-S first. c-o first. s

Compile: gcc-c first. s-o first. o (you can also directly compile the source code: gcc-c first. c-o first. o)

Executable: gcc first. o-o first (of course, this can also be done in one step: gcc first. c-o first)

 

Now we focus on the Link process. From the above analysis, we can see that the so-called link is to combine the target code, startup code, and library code to form executable code. The preceding example only contains one source file. If multiple files exist, multiple target codes are bonded with the startup code and the library code. So the question is: Can multiple target codes be easily bonded together?

 

To answer this question, you still have to go back to the source code analysis. After all, the target code is only the compiled version of the source code. Although the source code is separated into several parts and stored in different files, it must be consistent in the logic or context. That is to say, to re-store the code in several files into a single file, they still need to be "compatible", such as variables, functions, and so on, and cannot be repeated; for example, you can only have one main function.

 

However, we know that the maximum scope of variables and functions is the file scope .??? For example, how can we ensure that the variables in a file are directly used by other files and will not cause conflicts? The answer is the header file. The header file is the key to logically concatenate each split file.

Here is an example. In this example, I use C code to imitate the game "Stone scissors". 0, 1, and 2 represent stone, scissors, and cloth respectively. During the game, the program generates a random number and prompts the user to enter a number, and then determines whether to win or lose based on the rules. The complete code is as follows:

 

#include 
 
  #include 
  
   #include 
   
    int gen_rnd(void);void judge(int, int);int main(void){    int user, computer;    printf("Please input a number, 0 for stone, 1 for scissors, 2 for cloth and q for quit: ");    while(scanf("%d", &user) && user != 'q') {        if(user > 2 || user < 0) {            printf("Please input a number between 0 and 2: ");            continue;        }        computer = gen_rnd();        judge(user, computer);        printf("number: ");    }    return 0;}int gen_rnd(void){    int ret;    time_t t;    srand((unsigned)time(&t));    ret = rand() % 3;    return ret;}void judge(int user, int computer){    char *name[] = {"stone", "scissors", "cloth"};    int res = abs(user - computer);    if(res == 0)        printf("The computer is %s and you are %s, even\n", name[computer], name[user]);    else if(res == 1) {        if(user < computer)            printf("The computer is %s and you are %s, you win\n", name[computer], name[user]);        else            printf("The computer is %s and you are %s, you lose\n", name[computer], name[user]);    }    else {        if(user < computer)            printf("The computer is %s and you are %s, you lose\n", name[computer], name[user]);        else            printf("The computer is %s and you are %s, you win\n", name[computer], name[user]);    }}
   
  
 

 

File. c

 

There are three functions in the source code, which respectively represent different functions: main is the main function; gen_rnd () is used to generate random numbers to simulate computers; judge () is used to determine whether to win or lose. Each function is a function module. Now we divide this file into three parts: main. c gen_rnd.c judge. c. Each file contains only one function. As follows:

 

#include 
 
  #include 
  
   int gen_rnd(void);void judge(int, int);int main(void){    int user, computer;    printf("Please input a number, 0 for stone, 1 for scissors, 2 for cloth and q for quit: ");    while(scanf("%d", &user) && user != 'q') {        if(user > 2 || user < 0) {            printf("Please input a number between 0 and 2: ");            continue;        }        computer = gen_rnd();        judge(user, computer);        printf("number: ");    }    return 0;}
  
 
Main. c

 

 

 

#include 
 
  int gen_rnd(void){    int ret;    time_t t;    srand((unsigned)time(&t));    ret = rand() % 3;    return ret;}
 
Gen_rnd.c

 

 

#include 
 
 
void judge(int user, int computer) { char *name[] = {"stone", "scissors", "cloth"}; int res = abs(user - computer); if(res == 0) printf("The computer is %s and you are %s, even\n", name[computer], name[user]); else if(res == 1) { if(user < computer) printf("The computer is %s and you are %s, you win\n", name[computer], name[user]); else printf("The computer is %s and you are %s, you lose\n", name[computer], name[user]); } else { if(user < computer) printf("The computer is %s and you are %s, you lose\n", name[computer], name[user]); else printf("The computer is %s and you are %s, you win\n", name[computer], name[user]); } }

 

Judge. c 

 

As you can see, since it becomes a separate file, judge. c must include Otherwise, an error will be reported during compilation of the target file:

 

m@sys:~/program/C_codes$ gcc -c judge.c judge.c: In function ‘judge’:judge.c:8:9: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]         printf("The computer is %s and you are %s, even\n", name[computer], name[user]);         ^
In the same way, gen_rnd.c should include But main. c does not need this header file.
Now, we will generate the target file for them respectively:

 

Gcc-c judge. c main. c gen_rnd.c

This will automatically generate gen_rnd.o judge. o main. o in the current directory.

Then you can generate the executable file: gcc gen_rnd.o judge. o main. o-o exe

These three target files can be correctly bonded together because they still have logical connections: first, only main. the c file has a main function, which provides the correct entry. Secondly, each file can contain the required header file to correctly generate the target code. Again, because main. c calls the other two functions, so the prototype of the other two functions is declared, although the file does not contain their code, however, the code of the two functions in the Link stage is combined into the executable file. Similarly, printf () the Code of other functions will also be combined into executable files in the Link phase, that is, the so-called Linked Library file.

 

Related Article

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.