I wrote a minimal code to test the working of guard macros in C. I read that they prevent the header file to be read again by the compiler if it has done already. Here is my header file:
#ifndef TEST_H
#define TEST_H
#include<stdio.h>
int num=12;
#endif
Here is my main function:
#include"headers.h"
int main()
{
p2();
return 0;
}
Here is the p2 function called in main():
#include"headers.h"
void p2()
{
printf("p2 running\n");
}
- While compilation it is giving me error of redefinition of num. Should macro TEST_H not prevent multiple definitions error of num here ?
- Also if I replace
int num=12;withint num;, without any other modification, It does not show any error. Shouldint num;must not be a definition of num(as it will be initialized to 0) and compiler should again show same error of multiple definitions of num?
Let me answer to each of your questions:
The macro TEST_H prevents any multiple inclusion of the content of
headers.hfile in a translation unit, i.e. in a C source file. In your case, it works: you have only one definition ofnumin each C file. The raised error probably comes from the linker, which finds two definitions of the same variable in the linked code.If you replace
int num=12;withint num;, then it become a tentative definition as commented by @RobertoCaboni: to summarize, you authorize the compiler/linker to consider this instruction either as a definition (the first time it is encountered) or a declaration (the next times it is encountered). So you do not have any more error with multiple definitions. The initialization to 0 will depend on your linker configuration and/or your source code.