Dark Horse programmer--c Language's extern and static

Source: Internet
Author: User

Knowledge Points:

External functions: Defined functions can be accessed by this file and other files

1> all functions are external functions by default

2> external functions with the same name are not allowed

Intrinsic functions: Defined functions can only be accessed by this file and other files cannot be accessed

1> allows internal functions with the same name in different files

Static effects on functions:

1> defines an intrinsic function

2> declares an intrinsic function

The effect of extern on functions:

1> defines an external function in its entirety

2> completely declares an external function

(extern can be omitted, and functions declared and defined by default are external functions)

One, extern and function

If there are multiple source files (. c) in a program, the compilation succeeds in producing the corresponding multiple target files (. obj), which cannot be run alone, because these target files may be associated, for example, a.obj may call a function defined in C.obj. These associated target files are linked together to generate the executable file.

First to understand the 2 concepts:

    • External functions: If the function defined in the current file allows other files to be accessed, called, is called an external function. The C language stipulates that external functions with the same name are not allowed.
    • intrinsic function: If the function defined in the current file does not allow other files to be accessed, invoked, or used internally, it is called an intrinsic function. The C language specifies that different source files can have intrinsic functions with the same name and do not interfere with each other.

The next step is to show a function that calls another source file definition in a source file, such as calling the one function defined in one.c in MAIN.C.

1. First defines the one function in one.c

If you want this one function to be accessed by MAIN.C, then the one function must be an external function. The complete definition is to add the extern keyword.

However, this extern is as obsolete as the Auto keyword, which can be omitted, because by default all functions are external functions. We can simplify:

2. Next, I want to call the one function in one.c in the main function of MAIN.C

How can I invoke the one function in one.c? You may have 2 ideas:

Idea 1: Write one () directly in the main function;

This is certainly not possible, because the main function does not know the existence of one function, how to invoke it? This will be an error in the standard C compiler, but it is only a warning in Xcode.

Idea 2: Include the one.c file in the MAIN.C

We all know that the role of # include is purely a copy of the content, so the equivalent

Well, it looks like it's right. Oh, before the main function, you define one function, and then call the one function in the main function. It's syntactically right, so compiling is no problem. But this program is not likely to run successfully because of the error when linking. We have defined the one function in the one.c, and now in the MAIN.C to define the one function, C language rules do not allow the same name of the external function, the linker will find in One.obj and main.obj defined the same function, will directly error, Xcode error message is this:

Duplicate symbol _one is that one of the identifiers repeats, and linker refers to the linker.

The above 2 ideas are not feasible, in fact, the idea is consistent: let main function know the existence of one function. The correct approach should be to pre-declare the one function in front of the main function (see Clearly, it is a declaration, not a definition, the definition and the declaration are different).

3. Advance declaration of the one function in front of the main function

You want to take the external functions defined in the other source files and declare that the complete practice should be to use the extern keyword to denote "external functions" that refer to others

Running the program, from the console output, you can find that the "one function defined in ONE.C" has been successfully called by the "Main.c main function".

Someone might come up with an idea: what if there are other source files that define this one function, except one.c? What is the one function that the main function calls? Rest assured, there is absolutely no such situation, not just said, not allowed to repeat the definition of the same external function, or the linker will error, so there will only be an external one function.

This is what the extern keyword does to a function: it is used to define and declare an external function. In fact, extern and auto as waste, can be omitted completely. As a result, we can simplify this:

In order to develop in a modular way, in a formal project, we will write the declaration of one function to another header file, of course, the name of the header file is best meaningful and normative, such as called One.h. Later, who wants to call this one function, including one.h this header file is OK. So the final code structure is this:

Second, static and function 1. Define intrinsic functions

As can be seen from the above example, the one function defined in one.c can be accessed by other source files. In fact, sometimes we might want to define an "intrinsic function", which means that you don't want other files to access the functions defined in this file. This is very simple, you just need to add a static keyword when defining a function.

(We will modify the code based on the example above)

I added a static to the front of void One (), which represents an intrinsic function.

Then you will find that the program does not work, in the link when the error. The reason for the error is simple: We have called the one function defined in one.c in Main.c, but now one.c is an "intrinsic" function that does not allow access to other files. Let's take a look at the error message:

The 1th red box in the undefined symbols ... This means that the one identifier is not defined, that is, one is not found, and the 2nd Red Box linker indicates that the linker has an error.

But this program can be compiled successfully, because we declare the one function in front of the main function (the function declaration and definition is different), this function declaration can be understood as: in the syntax, cheat the main function, tell it that one function exists, So, from a grammatical point of view, the main function can call one function. Does the one function exist or is it defined? The compiler is no matter. In the compile phase, the compiler will only detect a single source file syntax is not reasonable, do not detect the function is not defined, only when the link to detect that the function does not exist, that is, there is no definition.

Let's discuss one more question, why is it possible to compile successfully in many cases, but when the link is wrong? As long as you understand the role of compiling and linking is good.

The so-called compilation, is to check each source file syntax is reasonable, and does not check the correlation between each source file, a source file compiled successfully generated a target file.

The so-called link, is to check the relationship of the target file, the associated target file is combined to generate the executable file.

After reading these 2 concepts, and then go back to think about the error of the previous report, it should be fully understood.

2. Declaring intrinsic functions

We can also declare an intrinsic function with static

1#include <stdio.h>2  3  Static voidtest ();4  5  intMainintargcConst Char*argv[])6  {7 test ();8      return 0;9  }Ten   One  Static voidTest () { Aprintf"the test function was called"); -}

A test function is defined in line 11th, an intrinsic function, followed by a declaration of the test function in line 3rd, and then the test () function can be called in line 7th.

Iii. Summary of static, extern and function

1.static

* When defining a function, add static at the leftmost side of the function to declare the function as an intrinsic function (also called a static function) so that the function can only be used in the file where its definition resides. If there are intrinsic functions of the same name in different files, they do not interfere with each other.

* Static can also be used to declare an intrinsic function

2.extern

* When defining a function, if you add the keyword extern to the leftmost side of the function, it means that the function is an external function that can be called by other files. The C language specifies that if you omit extern when defining a function, it is implied as an external function.

* In a file to invoke external functions in other files, you need to declare the external function in the current file with extern, and then you can use, where the extern can also be omitted.

First, in Java, the definition of global variables does not have strict location rules

A global variable can be defined at the very beginning of a class, or at the end of a class, and a method can access a variable defined after it.

As you can see, the test method defined in line 4th can access the variable a defined in line 8th, which is perfectly fine.

In the C language, the position of the global variable definition is limited.

By default, a function does not have access to the global variables defined after it

In the main function defined in line 4th, attempting to access the variable a defined in line 9th, the compiler immediately gave an error.

There are 2 ways to resolve this error:

The 1th approach: Define variable A before the main function

So the compiler won't bother you.

2nd approach: Advance declaration of variable A before the main function

That is, let the main function know that the existence of the variable A is OK, as to where the variable A is defined, the main function is not in the tube.

* Full variable declaration requires the extern keyword

Line 3rd is declaring variable A, and line 10th is defining variable A, again emphasizing that declarations and definitions are different. The 6th row is the variable a defined by line 10th.

Note: You cannot omit the definition of line 10th, leaving only the declaration of line 3rd, because extern is used to declare a variable that has already been defined.

Third, repeat the same variable definition

* In fact, you can also directly before the main function to define a

You may be surprised to see this, but the compiler won't get an error. In this case, the variable a of line 3rd and line 10th represents the same variable.

* And so on, if we write countless global variables int A; they represent the same variable.

The variable A in lines 3rd through 6th, 13th through 17th represents the same variable.

* Also note that we can also declare the global variable A as a local variable and then use!!!

Note: The 2nd, 5th, 6th, and 10th lines all represent the same variable. In fact, from line 6th A's color (light blue) can be seen, this a is still a global variable.

(This is the feature of Xcode, if the global variable is accessed inside the function, the global variable will show a light blue color, if the function inside the local variable is accessed, the local variable will show normal black.) Of course, different development tools have different display scenarios)

* However, if you remove the extern of line 5th, then the situation is completely different, and I believe you know what it is like to have programming experience.

The 2nd and 10th lines represent the same global variable, and the 5th and 6th lines are a local variable, with no half-dime relationship to the outside global variable. In fact, from the 5th, 6 line a color (black) can be seen as a local variable.

Iv. variable with the same name in different source files

As mentioned earlier, you are in a source file no matter how many times you write the global variable int A, they represent the same variable. There is also the fact that if there is also a global variable int a in another source file, then all global variables int A of the two source files, all of which represent the same variable.

Note: The global variable A in MAIN.C and test.c represents the same variable.

We can prove that:

First, define a function in test.c to see the value of a

Then in line 9th of MAIN.C, modify the value of a to 10, and then call TEST.C's test function to see the value of a in test.c.

The output of the console has proven everything.

* Of course, the extern keyword is still applicable, such as:

And

Or is:

And

In both cases, the global variable a used in test.c and MAIN.C still represents the same variable

Note that it is not allowed to use extern for all variable A of two files, the following is wrong:

And

Because extern is used to declare a variable that has already been defined, these two files are declared variables, no one defines the variable, and when the link is correct, the error will be:

The approximate error means: The identifier A is not defined

Five, the static keyword

But most of the time, we don't want the global variables in the source file to be shared with other source files, which is equivalent to a private global variable, then you have to use the static keyword to define the variable.

In so doing, the variable a of test.c and main.c represents different variables, which are not connected and do not interfere with each other. That is, MAIN.C cannot access variable A in test.c, so when a is modified to 10 in Main.c, a in test.c is still 0. Output result:.

In fact, static can also be used to modify local variables, this in the "variable type" said, no longer elaborated.

* Because MAIN.C has no access to variable A in test.c, the following notation is incorrect:

And

extern is used to declare a variable that has already been defined and can be accessed, although the variable A is defined in test.c, but the scope of variable A in test.c is limited to test.c file, MAIN.C does not have access, so the extern in Main.c is obsolete.

Error when linking: identifier A is not defined

Unless the MAIN.C itself defines a variable a, the extern is valid, but at this time the variable a in MAIN.C and test.c represents different variables, respectively.

Vi. Summary of Static and extern

1.extern can be used to declare a global variable, but it cannot be used to define a variable

2. By default, a global variable can be shared by multiple source files, which means that a global variable with the same name in multiple source files represents the same variable

3. If you add the static keyword when defining a global variable, the effect of static is to limit the scope of the global variable, to be used only in the file that defines the global variable, and not to interfere with the same name variable in other source files

Dark Horse programmer--c Language's extern and static

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.