Use of extern and extern "C"

Source: Internet
Author: User

1. Basic explanationExternIt can be placed before a variable or function to indicate that the definition of a variable or function is in another file, prompting the compiler to find its definition in other modules when it encounters this variable and function.

In addition,ExternYou can also specify links.

2 problem: the extern variable defines an array in a source file: Char A [6]. In another file, it is declared using the following statement: extern char * A. Excuse me, can this happen?

Answer and analysis: 1) No. Illegal access is reported when the program runs. The reason is that the pointer to type T is not equivalent to the array of type T. Extern char * A declares a pointer variable instead of a character array. Therefore, it is different from the actual definition, resulting in invalid access during runtime. Change the Declaration to extern char a [].

2) The example analysis is as follows. If a [] = "ABCD", the external variable a = 0x61626364 (the ASCII code value of ABCD), * A is obviously meaningless.

Obviously, the space (0x61626364) that a points to is meaningless and prone to illegal memory access.

3) This reminds us that we must strictly match the declared format when using extern. In actual programming, such errors are not uncommon.

4) extern is often used in variable declaration *. the C file declares a global variable. If the global variable is to be referenced, it is placed in *. H and use extern to declare.

3 problem: extern function 1

It is often seen that extern is placed before the function to become part of the function declaration. So, what is the role of the C language keyword extern in the function declaration?

Answer and analysis:

If the function declaration contains the keyword extern, it only implies that the function may be defined in other source files and has no other function. There is no obvious difference between the following two function declarations:

Extern int F (); and int f (); of course, this is still useful, that is, replacing include "*. h "to declare the function. In some complicated projects, I prefer to add the extern modifier before all the function declarations.

4 problem: extern function 2

When the function provider unilaterally modifies the function prototype, if the user does not know to continue to use the original extern statement, the compiler will not report an error during compilation. However, during the running process, a system error is often caused by missing or missing input parameters. How can this problem be solved?

Answer and analysis:

Currently, the industry does not have a perfect solution to deal with this situation. The common practice is that the provider provides external interface declarations in its own xxx_pub.h, and then the caller includes the header file, in this way, the extern step is omitted. To avoid such errors.

Baojian has a dual front. For the application of extern, different practices should be selected for different occasions.

5. Problem: extern "C"

When using C functions in the C ++ environment, the compiler often fails to find the C function definition in the OBJ module, resulting in a link failure. How can this problem be solved?

Answer and analysis:

During compilation, C ++ will combine function names and parameters to generate an intermediate function name to solve the problem of function polymorphism. c ++ does not, therefore, the corresponding function cannot be found during the link. In this case, the C function needs to use the extern "C" to specify the link. This tells the compiler to keep my name, do not generate an intermediate function name for the link for me.

The following is a standard syntax:

// In. # Ifdef _ cplusplus # If _ cplusplus extern "C" {# endif/* _ cplusplus */...

// Where the. h file ends # ifdef _ cplusplus # If _ cplusplus} # endif/* _ cplusplus */

Supplement: extern "C" usage extern is a key word creative product network in C/C ++ that indicates the range (visibility) of functions and global variables. it tells the compiler that the declared functions and variables can be used in this module or other modules.

1. For the extern variable, it is just a declaration of the variable, and it is not defining the allocation of memory space. If this variable is defined multiple times, a connection error occurs. 2. In general, the function and global variable referenced by this module to other modules are declared with the keyword extern in the module header file. That is to say, the C file defines that if the function or variable is open to the outside, it will be declared with extern in the H file. Therefore, you only need to include the H file for external files. In addition, this function cannot be found outside of the compilation stage, but no error is reported. This function is found in the target code generated by the definition module in the Link phase.

3. the keyword corresponding to extern is static. The global variables and functions modified by it can only be used in this module.

Variables and functions modified by extern "C" are compiled and connected in C language; compilation method when the extern "C" declaration is not added

First, let's take a look at how C-like functions are compiled in C ++.

As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. The name of the function in the symbol library after being compiled by C ++ is different from that in the C language. For example, assume that the prototype of a function is:

Void Foo (int x, int y );

After the function is compiled by the C compiler, its name in the symbol library is _ Foo, while the C ++ compiler generates names such as _ foo_int_int (different compilers may generate different names, but all adopt the same mechanism, and the new name is called "mangled name ").

A name such as _ foo_int_int contains the function name, number of function parameters, and type information. c ++ relies on this mechanism to implement function overloading. For example, in C ++, the void Foo (int x, int y) and void Foo (int x, float y) functions generate different symbols, the latter is _ foo_int_float.

Similarly, variables in C ++ support both local variables and class member variables and global variables. The class member variables of the program written by the user may have the same name as the global variables, which are distinguished. In essence, the compiler uses a unique name for the variables in the class when compiling, similar to the function processing. This name is different from the global variable name with the same name in the user program.

Connection method when extern "C" is not added

Suppose in C ++, the header file of module A is as follows:

// Module A header file modulea. h # ifndef module_a_h # define module_a_h int Foo (int x, int y); # endif

Reference this function in Module B:

// Module B implements the file moduleb. cpp # include "modulea. H" Foo (2, 3 );

In fact, in the connection phase, the connector looks for symbols such as _ foo_int_int from the target file modulea. OBJ generated by module!

Compilation and Connection Methods After the extern "C" clause is added

After the extern "C" statement is added, the header file of module A is changed:

// Module A header file modulea. h # ifndef module_a_h # define module_a_h extern "C" int Foo (int x, int y); # endif

In Module B's implementation file, Foo (2, 3) is still called. The result is:

(1) When module A compiles and generates the foo target code, it does not perform special processing on its name and uses the C language;

(2) When the connector looks for the Foo (2, 3) call for the target code of Module B, it looks for the unmodified symbol name _ Foo.

If the function in module A declares that foo is of the extern "C" type, and Module B contains the extern int Foo (INT X, int y ), module B cannot find the function in module A, and vice versa.

Therefore, we can summarize the true purpose of the statement "extern" C "in one sentence (the birth of any syntax feature in any language is not random and comes from the needs of the real world. When thinking about a problem, we should not just focus on how the language is made, but also ask why it is doing so and what the motivation is, so that we can better understand many problems ):

Realize mixed programming of C ++, C and other languages.

Understand the motivation for setting up extern "C" in C ++. Next we will analyze the common usage skills of extern "C.

4.Extern"C"

(1) To reference functions and variables in C language in C ++, the following processing must be performed when the C Language header file (assumed as cexample. h) is included:

Extern "C" {# include "cexample. H "}

In the header file of the C language, the external function can only be specified as the extern type. The C language does not support the extern "C" declaration. When the c file contains extern "C", a compilation syntax error occurs.

The source code of the three files in the example project of C ++ referenced by the author is as follows:

/* C header file: cexample. H */# ifndef c_example_h # define c_example_h extern int add (int x, int y); # endif/* C language implementation file: cexample. C */# include "cexample. H "int add (int x, int y)

{Return X + Y;} // C ++ implementation file. Call Add: cppfile. CPP extern "C" {# include "cexample. H "} int main (INT argc, char * argv [])

{Add (2, 3); Return 0 ;}

If C ++ calls a C language. DLL, when including. When the DLL header file or interface function is declared, add extern "C "{}.

(2) When referencing functions and variables in C ++ in C, the header file of C ++ needs to add extern "C ", however, you cannot directly reference this header file that declares extern "C" in C. You should only declare the extern "C" function defined in C ++ as the extern type.

The source code of the three files contained in the example project of C ++ is as follows:

// C ++ header file cppexample. h # ifndef cpp_example_h # define cpp_example_h extern "C" int add (int x, int y); # endif // C ++ implementation file cppexample. CPP # include "cppexample. H "int add (int x, int y)

{Return X + Y;}/* C implementation file cfile. c/* compilation errors: # include "cexample. H "*/extern int add (int x, int y); int main (INT argc, char * argv [])

{Add (2, 3); Return 0 ;}

Use of extern and extern "C"

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.