user2923229
user2923229

Reputation: 19

How to define a function with two struct parameters from two different header files?

Im using C. I have two header files (H1 & H2) with two different structs(S1 & S2) respectively. I am trying to define a function in H1 that takes S1 & S2 as its parameters. I do not have the flexibility to move around the structs between the header files.

function(S1,S2);

But how can I declare S2 as the second parameter of this function as it is in H2 not H1?

Upvotes: 1

Views: 558

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754720

In H1, have:

#ifndef H1_INCLUDED
#define H1_INCLUDED

#include "H2"

extern ... your_function(S1 arg1, S2 arg2);

#endif

In fact, if you only need structure pointers, you don't have to include H1 in H2; you can simply write:

#ifndef H1_INCLUDED
#define H1_INCLUDED

struct S2;

extern ... your_function(S1 *arg1, S2 *arg2);

#endif

The struct S2; line says "there is a structure type with tag S2 and I'm not going to tell you anything more about it". It is sufficient as long as the code in the header does not need to access members of the structure, which is highly likely, and as long as the functions take pointers to the structure type and not actual copies of the structure type.

See also:

Upvotes: 2

Alok Save
Alok Save

Reputation: 206606

You simply include the header file which defines the structure in your c file.

#include "H2.h"

Upvotes: 3

Related Questions