Kraken
Kraken

Reputation: 24213

How to include a specific header file without having a conflict

My Files are

main.c

#include"A.h"
#include"B.h"

A.c

#include"A.h"

B.c

#include"B.h"

I have a file with a couple of structures that I have defined that I am supposed to use in all the files i.e A.c , B.c, main.c and even the header files for A and B.

Hence I have

A.h and B.h both have

#include"struct.h"

Now, I see that in my main.c

I will have multiple declaration for both the structures, how do I get rid of this problem. What shall I change in my structure?

Thanks

Upvotes: 1

Views: 2607

Answers (4)

Leo Chapiro
Leo Chapiro

Reputation: 13984

Simply use so called header guard to be sure of including "struct.h" only once:

// struct.h
#ifndef STRUCT_H
#define STRUCT_H

struct ...{

}

#endif

Upvotes: 1

jrok
jrok

Reputation: 55395

Wrap the header files in include guards., like this:

#ifndef MYHEADER_H
#define MYHEADER_H

    // your definitions

#endif

Each header file should have its own guard with an unique name. The above preprocessor directives translated to english say something like: "If MYHEADER_H is not defined, then define it and paste the contents until #endif directive." This guarantees that a single header is included only once inside a single translation unit.

Upvotes: 1

Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

You can use a guard as such,

#ifndef MY_STRUCT
#define MY_STRUCT
#include "struct.h"
#endif

If you want to selectively take care of which parts should not be duplicated

Upvotes: 1

svk
svk

Reputation: 5919

Use include guards.

aheader.h:

#ifndef AHEADER_H
#define AHEADER_H

// ... rest of header here

#endif

bheader.h:

#ifndef BHEADER_H
#define BHEADER_H

// ... rest of header here

#endif

Upvotes: 7

Related Questions