redefine typedef in public headers

54 Views Asked by At

I am trying to define a typedef to a structure in private header file and redefine this in the public header as it is used as an argument to a function and as only the private header should be included for use, as in the main.c example. I have seen the done in a larger project but cannot seem to get this working in a test project. Creating the type in the main source file results in the error variable has incomplete type {typeName}

The basic example is seen below

fnc_private.h

#ifndef _FNC_PRIVATE_H_
#define _FNC_PRIVATE_H_

typedef struct fncStruct_t
{
    int a;
    int b;
} fncStruct_t;

#endif

fnc.h

#ifndef _FNC_H_
#define _FNC_H_

typedef struct fncStruct_t fncStruct_t;

int myFnc(fncStruct_t *h);

#endif

fnc.c

#include "fnc.h"
#include "fnc_private.h"

int myFnc(fncStruct_t *h)
{
    return h->a + h->b;
}

main.c

#include <stdio.h>

#include "fnc.h"

int main(void)
{
    fncStruct_t h = {3, 4}; // results in 'variable has incomplete type {fncStruct_t}'

    printf("sum = %d\n", myFnc(&h));

    return 0;
}

If I'm doing something stupid here, I cannot seem to see what it is. Thanks in advance.

2

There are 2 best solutions below

3
dbush On BEST ANSWER

main.c doesn't see the full definition of fncStruct_t, only a declaration, so it can't create a variable of that type.

What you can do is create a pointer to that type, then have a function in fnc.c that dynamically creates the object and returns it to you.

fnc.h

#ifndef _FNC_H_
#define _FNC_H_

typedef struct fncStruct_t fncStruct_t;

fncStruct_t *init(int a, int b);
int myFnc(fncStruct_t *h);

#endif

fnc.c

#include <stdlib.h>
#include "fnc.h"
#include "fnc_private.h"

int myFnc(fncStruct_t *h)
{
    return h->a + h->b;
}

fncStruct_t *init(int a, int b)
{
    fncStruct_t *h = malloc(sizeof *h);
    h->a = a;
    h->b = b;
    return h;
}

main.c

#include <stdio.h>
#include <stdlib.h>

#include "fnc.h"

int main(void)
{
    fncStruct_t *h = init(3, 4)

    printf("sum = %d\n", myFnc(h));
    free(h);

    return 0;
}
0
vjalle On

I guess in that larger project the equivalent of fnc.h included fnc_private.h. You can do the same here.

Otherwise the error message is completely normal. In main.c the details of the structure are not visible so it's an incomplete type.

It's possible to define new types, declare functions by just telling the compiler that it's a structure. It's equivalent to showing the declaration of functions. But when you want to create a variable from your structure type, or reference its members, the complete definition of the structure must be visible to the compiler.