Recently looking at a php extension source, compile the time encountered a problem:
LD 1 for Architecture x86_64
Take a closer look at the source code, found in the header file in the definition of global variables
Zend_declare_module_globals (XX)
Simple, so you can understand.
//T1.h#ifndef T1_h#defineT1_hintA =0;#endif//------------------//t1.c#include"T1.h"#include"t2.h"intMain () {return 0;}//-----------------//t2.h#include"T1.h"//Empty//----------------//t2.c#include"t2.h"//Empty//-------
So the first question, should #ifndef this macro prevent multiple definitions?
Answer: Yes. However, it is in a single compilation unit (wiki translation Unit).
We know that a complete compilation process is
ONE.C--- preprocessor , tmp.c ( temporary), COMPILER, One.obj, LINKE R -One.exe
These three processes, and during the precompilation phase, the include file is expanded, and we use the CC-E command to view the results of the t1.c precompilation:
? T CC-E t1.c #1 "t1.c"# 1 "<built-in>" 1# 1 "<built-in>" 3# 321 "<built-in>" 3# 1 "<command line>" 1# 1 "<built-in>" 2# 1 "t1.c" 2# 1 "./t1.h" 1intA =0;# 3 "t1.c" 2# 1 "./t2.h" 1# 4 "t1.c" 2intMainvoid){ return 0;}
Seeing the compiler unfold the t1.h, we see the definition of a.
In the pre-compilation results of t2.c, we also see the expansion definition of a:
? T CC-E t2.c #1 "t2.c"# 1 "<built-in>" 1# 1 "<built-in>" 3# 321 "<built-in>" 3# 1 "<command line>" 1# 1 "<built-in>" 2# 1 "t2.c" 2# 1 "./t2.h" 1# 1 "./t1.h" 1intA =0;# 2 "./t2.h" 2# 2 "t2.c" 2
So, for God's horse #ifdef (include guards) does not play a role in preventing redefinition?
The reason is that the include guards only works within the same compilation unit (the compilation process of a C file and an include file), and the compilation process is separate for the two compilation units, so it is not possible to perceive the #ifdefine content in the other.
t1.c, T1.s, t2.o *->- t.otu /T2.S-T2.O
Therefore, in the header file is not supposed to define the variable, should only declare.
So what if I want it?
If it's a function, someone gives you a way to add inline or static keywords. Or someone who's just doing it:
#ifdef define_globals #define extern#else#define extern extern#endifintint Global2;
So, back to the original question, the header file does not define the variable, and I do not see a similar special macro definition of how to deal with this problem, so how does he deal with it? Is it handled in the compile phase?
And wait for the next section ...
Defining variables in the C language header file