Thoroughly understand the extern keyword && global variable definition issues

Source: Internet
Author: User
Tags define function

Recently learning Lua, about LUA compiled place, because Lua is written in C, C language in C + + functions, need to use the extern "C" compile before, seemingly did not touch this knowledge, write a blog to commemorate, by the way the role of the extern keyword.


I. The role of extern "C"This is the first time I've seen it, because I've never had C + + to callC's function. There are some places to be aware of mixed programming for C + + and C languages. For example, if the following error occurs at compile time:
Error: The precompiled header file comes from an earlier version of the compiler, or the precompiled header is C + + and uses it in C (or vice versa)

This is because the C language and C + + precompiled header is different, if the C language file is less, you can use the C language file properties--------The precompiled header instead of using a precompiled header, you can solve the problem.


If you use the C-language function directly in the CPP file, the following error occurs:

>c++test.obj:error LNK2019: unresolved external symbol "int __cdecl ctest (int,int)" ([email Protected]@[email protected]), the symbol in function _wma In is referenced.

The error occurred at link stage, the connector did not find int_cdecl ctest (int int) This function, and we clearly wrote ctest this function. The reason is that C + + and C are compiled differently, C + + supports function overloading, so at compile time, the function name will usually add a lot of wonderful stuff, generally is to record overloaded information, specifically compiled into what needs to see the compiler's temper. The C language does not support overloading, so the compilation is relatively "pure", and we follow the C + + compiler to compile a C-language function, it will cause the above error.


At compile time, if want to contain C language east, in C language header file up and down add extern "C" can solve this problem.

Note: the extern "C" keyword combination is not supported in the C language, so it is necessary to add this by adding this to the section of the C language header file that is introduced by C + +. If you add it in the C language, the following error appears:

Error C2059: Syntax error: "String"

See an example of C + + mixed compilation C language functions:


C Language Header file:

#ifndef __cfile_h_#define __cfile_h_int ctest (int a, int b); #endif

C Language Implementation files:

#include "CFile.h" int ctest (int a, int b) {return a + B;}

C + + files:

C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>using namespace std;//use the extern "C" keyword, declare this thing is C language, do not use C + + way to//__ The Cplusplus is a built-in macro for CPP files and is compiled only if it is a CPP file. This writes better control over the compilation stream. #ifdef __cplusplusextern "C" {#endif # include "CFile.h" #ifdef __cplusplus}; #endifint _tmain (int argc, _tchar* argv[]) { int a = 1;int B = 2;cout<<ctest (A, b) <<endl;system ("pause"); return 0;}
If you write this, you can pass the compilation!

The results of the operation are as follows:

3
Please press any key to continue ...


About the extern "C" to note the place:

1. When using Lib or DLL written in C language, the included. h header needs to be written in the extern "C" {//header file}.

2. Do not write in the C language file because the C language does not support the extern "C" keyword.

3. Use ifdef __cplusplus in the CPP file to control the compilation stream and, if it is a CPP file, to compile the related operation.


There are two articles about the extern "C" that are very detailed:

Http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html

Http://www.cnblogs.com/yc_sunniwell/archive/2010/07/14/1777431.html


Two. The role of externThe extern keyword basically declares that the variable has been declared in another file (declaring a global variable or function), and if a variable with extern is encountered during compilation, it will look for its definition in other modules. Note, however, that it is just a declaration rather than a definition, that is, if you want to use this variable, you only need to include the header file where the variable definition is located. During the compile phase, although the function or variable is not found in this module, it does not cause an error, and the variable or function is found in the module defined at the time of connection.In short, extern is used to declare that this thing has been declared in other files. Both variables and functions can be declared using the extern function. However, the function does not use extern and the use of the extern keyword declaration is not much different. For variables, undefined errors occur if the global variable definition and use are not in a single file. If you redefine a variable with the same name in this file, a redefined error occurs. Therefore, this situation requires the use of the extern keyword to be declared in this file.
about extern and static: The two are actually incompatible, because the role of extern is to let the variable or function cross the file, and the function of static is to keep the scope of the variable or function in this file, so they cannot be used at the same time. The general definition of the static global variable is in the implementation file, and no longer runs into the header file to declare a copy.


Three. About Global variables
It seems that I used to do this stupid thing to put together definitions and declarations, it is convenient to define and declare global variables directly in the header file, but this is very bad, for the following reasons: 1. Code size increased by 2. If the header file is contained by multiple files, it will cause a redefinition error. 3. During the connection phase, there are multiple definitions that can cause errors in the function body to be found.
So let's be careful: declarations are made only in the header file, and the definitions are placed in the implementation file. A good way to do this is to declare it in the header file and use extern to define it in the implementation file. An example: StaticTest.h file
#ifndef __static_test_h_#define __static_test_h_//declares the variable (plus the extern keyword, which is just declared here, defined in other files) extern int num;//declaring the function void TestFunc (); #endif

StaticTest.cpp file
#include "stdafx.h" #include <iostream> #include "StaticTest.h" using namespace std;//define variable int num = 10;//define function void TestFunc () {Cout<<num<<endl;}

Main function file
C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>//references the StaticTest.h file, including the NUM declaration, so you can use the NUM variable and the TestFunc function directly in this file # Include "StaticTest.h" using namespace std;int _tmain (int argc, _tchar* argv[]) {TestFunc (); Cout<<num<<endl ; System ("pause"); return 0;}


When we use global variables defined in other files, there are several situations: 1. When defined in other CPP files, we need to use the extern keyword in this file to declare the variable in this document. 2. This global variable is defined in the. cpp file, but is already declared with the extern keyword in its corresponding. h file, so we can use this variable directly with this. h file. 3. In the worst case, the definition and declaration of this variable are all in the header file, so we can use this variable directly with the header file, but it is not recommended.









Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Thoroughly understand the extern keyword && global variable definition issues

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.