The #ifndef HEADER_H... construct only protects from inclusion of a
specific header file once from the SAME C-filer. Not from inclusion by
multiple C files.
In the header file, you should normally write
extern int p;
and then in one of the C files write
int p;
Or you can modify the files to look like:
--- header.h ---
#ifndef HEADER_H
#define HEADER_H
#if defined IMPLEMENTATION
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int p;
#endif
---------
--- main.c ---
#define IMPLEMENTATION
#include "header.h"
int main() {
...
}
----------
--- other.c ---
#include "header.h"
...
------------
/Per W
On Mon, 30 May 2005, Farzan Hajian wrote:
> Hi,
> Please help me with the following code. We have three files: a header file
> and two
> implementation files.
>
> // Source of "header.h"
> #ifndef HEADER_H
> #define HEADER_H
>
> int p;
>
> #endif
> --------------------------------
> // Source of "main.cpp"
> #include <cstdio>
> #include "header.h"
>
> int main()
> {
> printf("%i\n",p);
> return 0;
> }
> --------------------------------
> // Soruce of "func.cpp"
> #include "header.h"
> int func()
> {
> return p;
> }
>
> The compiler generates the error " multiple definition of 'p' ".
> What is wrong with the code?
> When the header file is included for the first time, the macro "HEADER_H"
> is defined
> but when the header file is included in the second implementation file,
> "HEADER_H" can not be recognized in the second file and "p" is define
|