Home > Software design >  Problem with structure and organization in big c project
Problem with structure and organization in big c project

Time:11-23

I started my first big c project, in which I divided the functionality of the program into different files. I ran in a situation where library include each other and there was some declaration problem.

sometingh like this:

in apha.h

#pagma once
#include "betha.h"

struct alpha
{
    int data;
    betha bb;
};

int fun1(apha a);

in betha.h

#pagma once
#include "alpha.h"

struct betha
{
    double data;
    double moreData;
};

int fun2(alpha a, betha b);

I found a solution in transferring all the struct in a separate file struct.h and it works fine. but I was wondering if there was a way to have the struct in their respective libraries because it would make more sense and be easier to work with.

CodePudding user response:

For starters it seems there are two typos in the header name

apha.h

that should be

alpha.h

and in this declaration

int fun1(apha a);

It seems you mean

int fun1(alpha a);

After including the header apha.h in a compilation unit you in fact have

struct betha
{
    double data;
    double moreData;
};

int fun2(alpha a, betha b);

struct alpha
{
    int data;
    betha bb;
};

int fun1(apha a);

As you can see the function func2 refers to the name alpha

int fun2(alpha a, betha b);

that was not yet declared.

You could use either the forward declaration

struct betha
{
    double data;
    double moreData;
};

struct alpha;

int fun2(alpha a, betha b);

or the elaborated type specifier in the function declaration

struct betha
{
    double data;
    double moreData;
};

int fun2( struct alpha a, betha b);
  • Related