C language/header file/define variables/duplicate definitions when compiling

It can be defined, but it is not recommended to define variables in the header file.


Because many .c files can contain .h files, this means that this variable will have a copy in many .c files. If this is a multi-file project, during the linking phase, the linker will complain that there are multiple global variables with the same variable name, resulting in link errors.


Therefore, the .h file generally can only contain global variable declarations, function declarations, and macro definitions. It is not recommended to define variables in the .h file.


If you declare a variable in a header file, and then call the header file in different source files, it will cause the compiler to report an error that the variable is defined repeatedly (even if #ifndef xxxxx is written).
The solution is to declare the variable in the corresponding .c file and extern the variable in the header file.
In example.c
int a = 0;

In example.h

extern int a;

Then other c files #include "example.h"are fine.

Guess you like

Origin blog.csdn.net/qq_36783816/article/details/112916516