Fanl Fanl - 1 month ago 9
C++ Question

How does the #ifndef deal with the globally declared variables and my own variables?

There is a question which make me puzzle. I know it is not right to do that ,but I don't know why. And how does the #ifndef #define #endif work.How the compliers deal with the varialbles like the following "a" and "b" ;

The code is simple:(myh.h):

#ifndef P_H
#define P_H
struct P{
int a;
};
int b;
#endif


another file s.cpp

#include"myh.h"
P a1;


the main.cpp:

#include<iostream>
#include"myh.h"
using namespace std;

int main()
{
P a2;
return 0;

}


The error is multiple definition of b; just as I know. I have two questions: 1.as some books said if you use #ifndef the compliers will not include it twice , then why the "b" seem be included twice .


  1. What is the differnce of "a" 、 "b"and "P". Why "a" and "P" have no question . I don't know wether I am right to consider "P" as a variable the same level with "b"? Or "P" is just a definition of type.



If It is the difference of local and global ,why is "P" right?

I am really puzzled. Pardern your time to help me. Thanks.

Answer

First, about the compilation:
You´ve to understand that the compiler will compile every cpp-file separately first
(before they go all together in a executable during the linking process)

If you have a file main.cpp and two times a #include <abc.h> in it,
you can prevent the second include to give errors with your #ifndef-usage.
If you have a main.cpp which includes a.h and b.h, but a.h includes b.h too,
#ifndef etc. will help too.

But: As cpp-files (together with included headers) are processed separately,
it won´t help if you include the same header file in different cpp files.

Ie. you may include headers as much as you want, but they shouldn´t contain variables.

About your second question: P is only a "description" what a "P" should be.
(every P has a int a. But at that time, there is no P.).
b is an actual int which can hold numbers...

Comments