Re: Header file included more than once?
- From: jt@xxxxxxxxxxx (Jens Thoms Toerring)
- Date: 9 Aug 2007 11:47:50 GMT
Pietro Cerutti <gahr@xxxxxxx> wrote:
suppose test1.c, test2.c and test.h
/*** BEGIN TEST.H ***/
#ifndef _TEST_H
#define _TEST_H
typedef struct
{
unsigned int code;
const char *name;
} test_struct;
test_struct structs[NOF_STRUCTS] =
{
{ 12, "twelve" },
{ 11, "eleven" }
};
int test_func(void);
#endif /* !_TEST_H */
/*** END TEST.H ***/
/*** BEGIN TEST1.C ***/
#include <stdio.h>
#include "test.h"
int main(void)
{
return (0);
}
/*** END TEST1.C ***/
/*** BEGIN TEST2.C ***/
#include "test.h"
int test_func(void)
{
return (2);
}
/*** TEST2.C ***/
gcc -ggdb -o test test1.c test2.c/var/tmp//ccZgBLuP.o(.data+0x0): multiple definition of `structs'
/var/tmp//ccLatz7e.o(.data+0x0): first defined here
Why is the header file parsed twice (and thus structs defined twice),
even when I started the header file with #ifndef etc etc statements?
You already got the answer, i.e. the files test1.c and test2.c get
compiled individually and a macro set in test1.c (via the included
file) doesn't exist anymore when the compiler is restarted to
compile test2.c and you thus end up with two instances of structs.
To avoid that never, ever define variables (or anything else) in
a header file. Define structs in one of the .c files and declare
it as extern in the other (or in the header file, it doesn't hurt
if a variable is both declared as extern and defined). An extern
declaration doesn't create an instance of structs, it just tells
the compiler that it is defined somewhere else, so it won't com-
plain that the variable doesn't exist.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.
- References:
- Header file included more than once?
- From: Pietro Cerutti
- Header file included more than once?
- Prev by Date: Re: call c++ function from c
- Next by Date: Re: fork on multiple cpu server
- Previous by thread: Re: Header file included more than once?
- Next by thread: Re: Header file included more than once?
- Index(es):
Relevant Pages
|