Usage analysis of extern "C"

Source: Internet
Author: User

  assuming the C + + library file is libtest.a and the header file of the library is test.h, write this in test.h: Before and after the function to be exported: extern "C" {void Test_func ();.}    &nbs p;  then use g++ to compile the source file of the link library, you can generate the C program can link the libtest.a. Of course, this libtest.a can also be linked by C + + programs.       But this only solves the problem of linking. When compiling a C program, you definitely want to use GCC, but GCC cannot recognize the extern "C" in Test.h and will report a syntax error. So, when compiling C programs, to remove extern "C", while linking C + + libraries and C's obj, you need to take the extern "C" of the g++ compiled link generated C + + library files.       So it is convenient to check if there is a __cplusplus definition in test.h, and if so, add extern "C" to enable g++ to generate C + + library files that can be linked to GCC. If not, do not extern "C", which is to allow GCC to parse the test.h correctly. While __cplusplus is a g++ predefined macro, GCC does not define the macro, which solves the contradiction between compilation and linking.   Test.h is as follows:   #ifdef __cplusplus extern "C" {#endif   void Test_func ();   #ifdef __cplusplus} #endif   extern "C" usage resolution       HTTP://BLOG.SINA.COM.CN/U/494A1EBC010004G5       C + + EX Tern the meaning of "C" Deep Exploration                                            1. Introduction   C + + language was originally created "A better C", but that does not mean that C + + Global variables and functions similar to the C language are compiled and connected in exactly the same way as the C language. As a language intended to be compatible with C,   C + + retains some of the characteristics of the procedural language (known as "not completely object-oriented"), so it can define global variables and functions that do not belong to any class. However, C + + is, after all, an object-oriented programming language  , in order to support the overloading of functions, C + + for global functions of the processing method and C are significantly different.       2. From the standard header file   an enterprise has given the following interview questions:   face question   Why standard header files have similar structure below.       #ifndef __incvxworksh       #define __INCVXWORKSH        #ifdef __cplusplus       extern "C" {      #endif     &NBSP ; /*...*/      #ifdef __cplusplus      }       #endif   & nbsp;   #endif/* __incvxworksh *   Analysis   Obviously, the compiled macros in the header file "#ifndef __incvxworksh, #define __INCVXWORKSH, #endif "Prevents the header file from being repeatedly referenced.   then   #ifdef __cplusplus   extern "C" {  #endif   #ifdef __cplusplus &nbsP What is the role of   #endif  ? We will come in the following one by one ways.       3. Deep disclosure extern "C"   extern "C" contains a double meaning, literally: First, the object modified by it is "extern"; second, the target being modified by it is "C". Let's take a detailed interpretation of this twofold meaning.   A function or variable that is qualified by extern "C" is an extern type;    extern is a keyword that indicates the scope (visibility) of functions and global variables in the C + + language, and the keyword tells the compiler that The functions and variables that they declare can be used in this module or in other modules. Remember the following statement:   extern int A;   is just a declaration of a variable that is not defined as variable A and does not allocate memory space for a. Variable A can only be defined once as a global variable in all modules, otherwise there will be a connection error.   Typically, the module's header file provides the keyword extern declaration for functions and global variables that are referenced by this module to other modules. For example, if module B wants to refer to the global variables and functions defined in module A, just include the header file for module A. In this way, when a function in module A is called in Module B, module B cannot find the function in the compile phase, but it does not complain; it will find this function in the connection phase from the object code generated by module a compilation.   the keyword corresponding to extern is static, and global variables and functions that are modified by it can only be used in this module. Therefore, a function or variable can only be used by this module, it cannot be decorated by extern "C".   variables and functions that are decorated by extern "C" are compiled and connected in a C language;   How to compile without extern "C" Declaration   first See how C + + functions in C + + are compiled.   As an object-oriented language, C + + supports function overloading, while programming language C does not. A function is compiled by C + + in a symbol library with a different name than the C language. For example, suppose the prototype of a function is:   void foo (int x, int y);   The function is compiled by the C compiler in the symbol library name is _foo, and C + + compiler will produce a name like _foo_int_int (different compiler may produce different names, but all using the same mechanism, the resulting new name is called "mangleD name ").   _foo_int_int names such as function names, function parameters and type information, C + + is to rely on this mechanism to implement the function overload. For example, in C + +, the function void foo (int x, int y) is not the same as the symbol generated by the compilation of void foo (int x, float y), which is _foo_int_float.   Similarly, variables in C + + support class member variables and global variables in addition to local variables. The class member variable of the program that the user writes may have the same name as the global variable, and we use the "." to differentiate. In essence, the compiler, when compiling, is similar to the processing of a function, and a unique name for a variable in a class that is different from the name of a global variable with the same name as the user program.   Connection mode without extern "C" declaration   assuming that in C + +, module A's header file is as follows:  //Module A header file moduleA.h   #ifndef module_a_h   #def ine module_a_h   int foo (int x, int y);   #endif   Reference this function in module B:  //module B implementation 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 A.   After the compilation and connection after the declaration of extern "C"   plus extern "C" declaration, module A's header file becomes:  //Module A header file moduleA.h   #ifndef module_a_h &N Bsp #define MODULE_A_H   extern "C" int foo (int x, int y);   #endif   still calls Foo (2,3) in the implementation file of Module B, and the result is that   (1) module A compiles the object code for Foo without special treatment of its name, using the C language;   (2) connector When looking for the Foo (2,3) call for the target code for module B, you are looking for an unmodifiedSymbol name _foo.   If the function in module a declares that Foo is an extern "C" type, and Module B contains extern int foo (int x, int y), module B cannot find the function in module A and vice versa.   So, you can generalize the true purpose of the declaration of extern "C" in one sentence (the birth of any grammatical feature in any language is not random, it comes from the demand-driven of the real world.) When we think about problems, we can't just stay in the language, and ask why it does it, what the motivation is, so that we can understand a lot more deeply:   Implement mixed programming with C + + and other languages.   understand the C + + in the creation of extern "C" motivation, we are below to specifically analyze the extern "C" the usual use of skills.       4.extern "C" usage   (1) in C + + to refer to the functions and variables, in the C language header file (assumed to be cExample.h), you need to do the following:   extern "C"   {  #include "cExample.h"  }   while in the header file of C, the external function can only be specified as an extern type, and the extern "C" declaration is not supported in C language, and Exter is included in the. c file. N ' C ' will cause a compilation syntax error.   I wrote the C + + reference to the example project contains the source code of the three files as follows:  /* C language header file: cExample.h/  #ifndef c_example_h   #define C_examp Le_h   extern int add (int x,int y);     //Note: write extern "C" int add (int, int); can also   #endif  /* C language Implementation file: CEXAMPLE.C *   #include "cExample.h"   int Add (int x, int y)   {&NB  Sp return x + y;  }  //C + + implementation file, calling Add:cppFile.cpp   extern "C"   {  #include "cExample.h"        //NOTE: This is inappropriate, if this Sample compilation pass, replace the extern "C" int add (int, int); can be     int main (int argc, char* argv[])   {  Add (2,3);   return 0;  }   if C + + When you invoke a. dll written in a C language, you should add extern "C" {} When you include the header file for the. dll or when declaring an interface function.   (2) when referring to functions and variables in C + + language, C + + header files need to add extern "C", but in C language can not directly refer to the declaration of extern "C" of the header file, you should only the C file in C + + defined in the extern "C" function is declared as an extern type.   I write the C reference + + Function Example project contains the source code of three files as follows:  //c++ header file cppExample.h   #ifndef cpp_example_h   #define Cpp_exa Mple_h   extern "C" int Add (int x, int y);   #endif  //c++ implementation file CppExample.cpp   #include "cppExample.h"   int Add (int x, int y)   {&nbsp  ; return x + y;  }  /* C implementation file cfile.c  /* This will compile an error: #include "cExample.h"/  extern int Add (int x, int y);   int main (int argc, char* argv[])   {  Add (2, 3);   return 0;  }   IFAn in-depth understanding of the role of extern "C" in the compile-and-connect phases described in section 3rd will give you a real understanding of the idioms in this section that refer to C functions and C C + + functions from C + +. The sample code given in section 4th requires special attention to detail.  

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.