wrote:
> red floyd wrote:
>
>>>Any link to a website explaining this behaviour of #ifdef / #ifndef ?
>>
>>That's not a preprocessor issue, it's the ODR (one definition rule).
>
>
> To me, that doesn't explain why
> #ifndef FOO
> #define FOO
> class foo {
> foo(){};
> ~foo(){};
> };
>
> int test;
> #endif
>
Let's say that you include this file in two source files. What happens?
a) The class foo gets its declaration. Good, now you can create foo objects.
b) The integer test gets allocated. Once in one file and once in the second file.
Everything is fine until the link stage. The linker will try to make sense of all and will see *two* instances of int test. Which one to use? Nobody will ever be able to answer that.
The solution,
extern int test;
Goes in the header. That will tell to the compiler: There is a variable called test that is to be used, but it is only declared here. Its definition will be done somewhere else.
Then, in one of your source files, you define this variable on the normal way.
When you compile, you can refer to this variable in any source code that uses the include file, but at link time, only one instance will exist. At this point, no link error. Hooray!
I hope I was clear.
Regards,
Marco