C Language Note header file and link (i)

Source: Internet
Author: User

<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " ><span style= "FONT-SIZE:18PX;" > Although I have been using the # include command to include the header file, it is not quite clear how the header file works. I studied it today. </span></span>

First, in large projects, only one source file is not enough, the huge amount of code needs to be placed in several files, of course, the main purpose of separate storage is to facilitate modularity. We separate the code into different files according to different functions or functions, so when one of the features changes, only the relevant files need to be recompiled, without having to compile all the source files for the entire project.

However, this poses a problem: can a variable or function defined in a file be used in another file? Or will a variable with the same name in two files cause a conflict?

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

First, through the preprocessor, replace the Macro command in the file;

Then through the compiler, generate assembly code;

Then there is the assembler, which generates the binary target code, but the target code is still not executed, and it lacks the boot code (the interface between the program and the operating system) and the library code (such as the entity code of the printf function);

Finally, through the linker, link the related code, generate the final executable code.


Since the mention of the compilation, we have to introduce the C language compiler GCC, if we have written a source file first.c, then corresponding to the above steps, gcc command parameters are as follows:

Precompiled: Gcc-e first.c-o first_1.c (Note: the-o option is used to specify the file name of the build result)

Compilation: Gcc-s First.c-o First.s

Compilation: Gcc-c First.s-o FIRST.O (can also be directly compiled Source: gcc-c first.c-o FIRST.O)

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


Now we focus on the link process. As you can see from the above analysis, the so-called link is to combine the object code, startup code and library code together to form executable code. This is the case where there is only one source file, and if there are multiple files, glue the multiple target code together with the startup code and library code. So the question is: can multiple target codes really be glued together casually?


To answer this question, you still have to go back to the source code analysis, after all, the target code is only the source code compiled version. Although the source code is separated into several parts and placed in different files, it must be consistent in the logic or context. That is, to put the code in a few files back to a file, they still want to remain "compatible", such as variables ah, function ah and so on, can not be repeated, such as can only have a main function.


However, we know that the scope of variables and functions, the largest is the scope of the file.??? For example, how to ensure that a variable in a file is also used directly by other files and does not cause conflicts? The answer is the header file. A header file is the key to logically string together the files that are being split.

Now give an example, in this example, I use C code to imitate the game "stone Scissors Cloth", 0, 1, 2 respectively represents the stone, scissors, cloth. During the game, the program randomly generates a number, prompts the user to enter a number, and then makes a winning or losing judgment according to the rules. The complete code is as follows:

#include <stdio.h> #include <math.h> #include <stdlib.h>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 I            Nput 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 your is%s, even\n", Name[computer], Name[user]); else if (res = = 1) {if (User < computer) printf ("The computer is%s and you were%s, you win\n", NamE[computer], Name[user]);    else printf ("The computer is%s and you were%s, you lose\n", Name[computer], Name[user]); } else {if (User < computer) printf ("The computer is%s and you were%s, you lose\n", Name[computer        ], Name[user]);    else printf ("The computer is%s and you were%s, you win\n", Name[computer], Name[user]); }}

File.c


There are three functions in the source code, which represent different functions: main is the main function; Gen_rnd () generates a random number to simulate a computer; Judge () is used to determine winning or losing. Each function is a function module, now we divide this file into three, respectively, Main.c gen_rnd.c judge.c, each file only holds one function. as follows:

#include <stdio.h> #include <math.h>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 num ber between 0 and 2: ");            Continue;        }        Computer = Gen_rnd ();        Judge (user, computer);        printf ("Number:");    }    return 0;}
main.c


<span style= "FONT-SIZE:12PX;" > #include <stdlib.h>int gen_rnd (void) {    int ret;    time_t T;    Srand ((unsigned) time (&t));    ret = rand ()% 3;    return ret;} </span>
GEN_RND.C

<span style= "font-family:arial, Helvetica, sans-serif;font-size:12px;" > #include <stdio.h></span>
<span style= "FONT-SIZE:12PX;" ></span><pre name= "code" class= "plain" >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 your is%s, even\n", Name[computer], Name[user])    ; else if (res = = 1) {        if (user < computer)            printf ("The computer is%s and you were%s, you win\n", Name[computer], Name[user]);        else            printf ("The computer is%s and you were%s, you lose\n", Name[computer], Name[user]);    }    else {        if (user < computer)            printf ("The computer is%s and your is%s, you lose\n", Name[computer], Name[user] );        else            printf ("The computer is%s and you were%s, you win\n", Name[computer], Name[user]);}    }

judge.c

As you can see, as a separate file, judge.c must include the <STDIO.H> itself, otherwise the target file will be compiled with an error:

[Email protected]:~/program/c_codes$ gcc-c judge.c judge.c:in function ' Judge ': Judge.c:8:9:warning:incompatible impli  CIT Declaration of built-in function ' printf ' [enabled by default]         printf ("The computer was%s and you are%s, even\n", Name[computer], Name[user]);         ^
In the same way, gen_rnd.c to include <stdlib.c&gt, while MAIN.C does not need the header file.
Now, let's generate the target file for it separately:

Gcc-c judge.c main.c GEN_RND.C

This will automatically generate GEN_RND.O JUDGE.O in the current directory MAIN.O

You can then generate the executable file: gcc gen_rnd.o judge.o main.o-o exe

The three target files can also be properly glued together because they still have a logical connection: first, only the MAIN.C file has a main function, which provides the correct entry, and secondly, each file can contain the required header files, so that the correct generation of the respective target code again, because main.c to invoke the other two functions, it declares the prototype of the other two functions , Although the file does not have their code, but in the link phase two function code will be combined into the executable file, the same reason, The code for functions such as printf () is also grouped in the executable file during the link phase, known as the link library file.


C Language Note header file and link (i)

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.