Home  >  Article  >  Backend Development  >  How to use extern keyword in C/C++

How to use extern keyword in C/C++

little bottle
little bottleforward
2019-04-29 10:56:543486browse

This article introduces the usage of extern keyword in C/C. It mainly talks about the usage when modifying variables. You can refer to it. , hope it helps you.

1. Basic explanation
extern can be placed before a variable or function to indicate that the definition of the variable or function is in another file, prompting the compiler to encounter this variable or function When looking for its definition in other modules. In addition, extern can also be used to link specifications.
extern has two functions: (1) When it is used together with "C", such as: extern "C" void func(int a); it tells the compiler to follow the rules of C when compiling the func function name. To translate the corresponding function name instead of C. Regarding this point, you may be able to find the answer in the book "In-depth Exploration of the C Object Model"; in addition, there is a backtrace function under Linux that can print stack information and view the C translated function name (this function is used in the muduo library) .
 (2) When extern is not used together with "C" to modify a variable or function, such as in the header file: extern int g_Int; its function is to declare the scope of the function or global variable keyword, and the declared Functions and variables can be used in this module or other modules, remember that it is a declaration not a definition!
2. When extern modifies variables
The correct way to use it is: define the variable in the .c file and declare it in the corresponding .h file.
We determine whether it is a declaration or a definition by whether memory space will be allocated for the variable (strictly speaking, it is simply allocating memory and does not include the initialization part). So does the sentence int i; declare or define it? It is both a statement and a definition. If we use this sentence in the test.h file, once i is defined in other files (e.g.1), or the file is included repeatedly (e.g.2), a redefinition error will occur.

/*
	e.g.1 	以下为3个文件
*/
//test.h
int i;

//test2.h
int i;

//main.cpp
#include "test.h"
#include "test2.h"
int main()
{
	return 0;
}
/*
	e.g.2 	以下为3个文件
*/
//test.h
int i;

//test2.h
#include "test.h"

//main.cpp
#include "test.h"
#include "test2.h"
int main()
{
	return 0;
}

Related tutorials: C video tutorial

The above is the detailed content of How to use extern keyword in C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:What is reflection in c#?Next article:What is reflection in c#?