1

I'm trying to experiment with opaque data types to get an understanding of them. The main problem is that I keep getting an 'incomplete' error.

main.c

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

int main()
{
    setfnarp(GOO,5);
    int loogaboo = getfnarp(GOO);

    printf("%i", loogaboo);
    return 0;
}

fnarpishnoop.c

#include "blepz.h"

struct noobza {
    int fnarp;
};

void setfnarp(struct noobza x, int i){
    x.fnarp = i;
};

int getfnarp(struct noobza x){
    return x.fnarp;
};

blepz.h

struct noobza;

void setfnarp(struct noobza x, int i);

int getfnarp(struct noobza x);

struct noobza GOO;

I clearly don't understand something here and I was hoping someone could help me figure out how opaque data types are implemented if the whole point of them is that you have a hard time finding actual code for them.

thepufferfish
  • 441
  • 4
  • 17
  • One thing you should usually not do, is declare variables in header files. In this case, don't put `struct noobza GOO` in the header file. Since you only use it in `main.c`, declare it there. That should also help you understand why you can't use `struct noobza GOO;` in `main.c`, since only `fnarpishnoop.c ` knows what the struct looks like. However, you can use a pointer to an incomplete type, because pointers have a fixed size anyway, The compiler doesn,t have to know what the actual struct that is pointed too looks like. So basically, delete the last line of `blepz.h` and fix according.y. – Cheatah Aug 11 '19 at 08:34
  • @Cheatah Granted, by rights, if I was using `struct noobza GOO;` in more than `main.c` I would have to put it in a header files to give it a global scope, no? – thepufferfish Feb 10 '20 at 03:00

1 Answers1

3

Using a struct that you haven't declared the contents of gives an "incomplete type" error, as you have already mentioned.

Instead, use a pointer to the struct and a function that returns a pointer to the struct, like this:

struct noobza;

struct noobza *create_noobza(void);

void setfnarp(struct noobza *x, int i);

int getfnarp(struct noobza *x);

struct noobza *GOO;

...

#include <stdlib.h>
#include "blepz.h"

struct noobza {
    int fnarp;
};

struct noobza *create_noobza(void)
{
    return calloc(1, sizeof(struct noobza));
}

void setfnarp(struct noobza *x, int i){
    x->fnarp = i;
};

int getfnarp(struct noobza *x){
    return x->fnarp;
};

...

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

int main()
{
    GOO = create_noobza();
    setfnarp(GOO,5);
    int loogaboo = getfnarp(GOO);

    printf("%i", loogaboo);
    return 0;
}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76