简体   繁体   中英

making library: conflicting types in header and source file

I have trouble understanding c header files and source files. I have:

something.c

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

typedef struct {
    int row, col;
} point;

point
whereispoint(point **matrix, int rows, int cols)
{
   ..... Does something ....
   printf("something...");
}

something.h

typedef struct point * p;

p whereispoint(p **matrix, int rows, int cols);

main.c

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

int
main(void)
{
   int row, col;
   p **matrix=malloc(bla, bla);
   .....Something.....
   p=whereispoint(matrix, row, col);
   return 0;
}

Now when I don't actually know how to compile this... I tried gcc -c main.c something.c but that doesn't work, I tried to compile separately gcc -c main.c and gcc -c something.c then main.c works but something.c does not.

I am actually trying to make a library out of something.c but as I am not able even to compile it to object code I don't know what to do. I guess there is something wrong with the struct type and the typedef of it in something.h but I can't figure out what...

In the header, the function whereispoint() is declare as returning a struct point* (the typedef p ) but the definition returns a struct point , not a pointer.

Personally, I find typedef pointers confusing and think it is clearer in the code if * is used to denote a pointer:

/* header */
typedef struct point point_t;

point_t* whereispoint(point_t** matrix, int rows, int cols);

/* .c */
struct point {
    int row, col;
};

point_t* whereispoint(point_t** matrix, int rows, int cols)
{
   ..... Does something ....
   printf("something...");
   return ??;
}

The following:

typedef struct {
  int row, col;
} point;

typedefs a nameless struct to the type point.

In something.h, you then typedef "struct point" (an undefined struct type reference) to "*p".

Typically, you should define all your "interface types" in the header file, instead of trying to hide the implementation (C needs to know the implementation to access anything).

Try doing something like this in something.h:

typedef struct point {
  int row, col;
} *p;

Or, if you are unsure exactly how typedefs work, simply do:

 struct point {
  int row, col;
}

That declares a struct type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM