How to use extern in C language

The code modified in the afternoon has not been compiled, and it is prompted to repeat the definition. I found that the reason is that the use of global variables does not use extern declarations. Here I will record the use of extern to deepen my memory.

extern is a keyword that declares a variable or function (tell the compiler that you should not rush to report an error first, this variable or function is defined elsewhere, you can look for it elsewhere, either at the back of this file or in the reference in other documents)

function declaration

The interface provided by the .c file will be declared in .h, but the extern keyword will not be displayed, because for functions, there is no function body, and it is a declaration by default. It doesn't matter if you add extern or not, execute always find the place where the function is defined

variable declaration

It is different for variables, as follows:

int a;                // 定义一个变量,无论在c还是h文件中
extern int a;    // 声明一个变量

If the extern keyword is not added to the h file, a (global) variable is also declared. After the h file is referenced multiple times, a duplicate definition error occurs. Even if the .h file is wrapped with #ifdef, it cannot be solved.

This article is written very clearly, reference: https://blog.csdn.net/csdnwei/article/details/51836182

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733837&siteId=291194637