[C/C++] Include headers with crossed references

Hi fellows,

To instantiate a struct (created in a header) in more than one source file the first thing that must be done is use a guard directive #ifndef. It will make gcc export data types and function signatures only once (according to the Makefile order). Meanwhile, if you need that a struct in a header h1 has a pointer to a struct in a header h2, which already has a pointer to a struct from h1 it will result in an error since gcc cannot resolve header cross reference (when gcc is processing header h1, it will find the #include h2 and when it try to create the struct h2 it will no find the type h1 returning the error: “expected specifier-qualifier-list before h1”). The first thing is rethink in the solution design. To overcome this, one alternative is forward struct declaration. Follows an example:


#ifndef H1_H
#define H1_H
struct h1;
typedef struct h1 h1;
#include "h2.h"
struct h1 {
	h1 *v1;
	h2 *v2;


#ifndef H2_H
#define H2_H
struct h2;
typedef struct h2 h2;
#include "h1.h"
struct h2 {
	h1 *v1;
	h2 *v2;


#include "h1.h"
#include "h2.h"
int main() {
	h1 v1;
	h2 v2;	
	return 0;

See ya!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: