0
votes

Can you explain why the struct Test is incomplete and how to remove the error? Is the error related to declaration in test.h or to definition in test.c? I tried to move the definition code to header file but then createTest does not know type Test or if I move the function to header there is the error multiple definition of createTest

test.h

typedef struct STest Test;

test.c

typedef struct STest {
    int v;
    char *str;
}Test;



Test *createTest(int v,char *str) {
    Test *t=(Test*)malloc(sizeof(Test));
    t->v=v; // error
    t->str=str;  // error
    return t;
}

main function (main.c)

error: main.c|44|error: dereferencing pointer to incomplete type

4
In addition to the answers below, if you call createTest() from main.c you will also need the function prototype Test *createTest(int v,char *str); in test.h - Weather Vane

4 Answers

0
votes

If you don't define the structure in the header file it will not be visible from your main.c.

You need to do the following

Point 1. Put the structure definition in the test.h header file. use include guard also.

#ifndef __MY_HDR_H_
#define __MY_HDR_H_
typedef struct STest {
    int v;
    char *str;
}Test;
#endif    //__MY_HDR_H_

[EDIT: Also, you need to add the function prototype for createTest() in the .h file]

Point 2. include test.h in test.c and main.c.

Point 3. Compile using

gcc main.c test.c -o output

Standard Warning : Please do not cast the return value of malloc() and family.

1
votes

Put

typedef struct STest {
    int v;
    char *str;
} Test;

into test.h.

typedef struct STest Test only says that Test is another name for struct STest. At the moment, that's all that main.c knows. Especially, main.c doesn't know which members the struct has. That sounds quite incomplete to me.

0
votes

Place the code in the header file.

typedef struct STest {
int v;
char *str;
} Test;

Because compiler doesn't know to dereference that.

Hint: Then don't cast the result of malloc.

0
votes

You seem to define Test twice.

In test.h you do

typedef struct STest Test;

Inside test.c remove the typedef and just do:

struct STest {
  int v;
  char *str;
};

A full example below:

To define an opaque type, a type which is know in detail only to the translation unit implementing its functions, you might take the following approach:

opaque.h

#ifndef OPAQUE_H
#define OPAQUE_H

typedef struct S T;

T * createT(int, char *);


#endif

opaque.c

include <stdlib.h>

#include "opaque.h"

struct S
{ 
  int i;
  char * p;
};

T * createT(int i, char * p)
{
  T * t = malloc(sizeof *t);

  if (NULL != t)
  {
    t->i = i;
    t->p = p;
  }

  return t;
}

And use it like follows:

#include "opaque.h"

int main(void)
{
  T * t = createT(0, NULL);
}