Home > Blockchain >  struct declared in tools.h and defined in tools.c. Can't link them to main.c
struct declared in tools.h and defined in tools.c. Can't link them to main.c

Time:11-13

file tools.h:

//some macro definitions

struct name;

//other function prototypes

file tools.c:

#include "tools.h"

struct name
{
    FILE *src;
    int value;
}


//definitions of functions declared in tools.h

file main.c:

#include <stdio.h>
#include "tools.h"

int main()
{
    struct name *ptr;
    ptr = malloc(sizeof(struct name));
    ptr->FILE = fopen(filename, "r");
    ptr->value = 12;
    ...
}

  1. At first, I built tools.o by using:
    $ gcc tools.c -c
    Without any error or warning, tools.o was built in the current directory.

  2. Now, I tried to build executable by using:
    $ gcc main.c tools.o -o exe
    and I got errors of same type (all the errors were of same type, caused due to accessing the struct element). Here's the sample of that error I got:

main.c: In function ‘main’:
main.c:17:22: error: invalid use of undefined type ‘struct name’
   17 |   buffer = malloc(ptr->value 1);

Please explain why this happened and what wrong I did while linking or in my code.

CodePudding user response:

tools.h file

#ifndef TOOLS_H
#define TOOLS_H

#include <stdio.h>

struct name
{
    FILE *src;
    int value;
};

int foo(struct name*);
struct name *bar(double, FILE*, const char *);  //prototypes of functions defined in tools.c
#endif

tools.c


#include "tools.h"

int foo(struct name*)
{
   /* ... */
}

struct name *bar(double, FILE*, const char *)
{
   /* ... */
}

CodePudding user response:

Looks like you have some confusion with regards to forward declaration of a structure and a structure declaration (which defines a type).

From Forward declaration:

a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.

In tools.h, this

struct name;

is forward declaration of structure struct name. Note that, it declares an incomplete type because the specification [list defining the content] of struct name is unknown at this time.

You have included the tools.h in main.c and when compiling main.c compiler does not find the specification of struct name and hence, throwing error on the statements using it.

In tools.c, you are declaring the struct name (which defines a type):

struct name
{
    FILE *src;
    int value;
};

when compiling tools.c, compiler knows about the specification of structure struct name and hence, it's compilation is successful.

The other post [by @0___________] gives the appropriate way to solve this problem.

  • Related