0

我无法理解 c 头文件和源文件。我有:

某事.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...");
}

某事.h

typedef struct point * p;

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

主程序

#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;
}

现在,当我实际上不知道如何编译它时……我试过gcc -c main.c something.c 了,但这不起作用,我尝试单独编译gcc -c main.cgcc -c something.c 然后main.c工作,但something.c没有。

我实际上是在尝试用 something.c 创建一个库,但由于我什至无法将其编译为目标代码,所以我不知道该怎么做。我猜something.h中的结构类型和它的typedef有问题,但我不知道是什么......

4

2 回答 2

2

在标头中,函数whereispoint()被声明为返回 a struct point*(the typedef p) 但定义返回 a struct point,而不是指针。

就个人而言,我发现typedef指针令人困惑,并认为如果*用于表示指针,代码中会更清楚:

/* 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 ??;
}
于 2012-11-01T17:49:10.327 回答
0

以下:

typedef struct {
  int row, col;
} point;

typedefs 一个无名结构到类型点。

然后在something.h 中,将“struct point”(未定义的结构类型引用)类型定义为“*p”。

通常,您应该在头文件中定义所有“接口类型”,而不是试图隐藏实现(C 需要知道实现才能访问任何内容)。

尝试在 something.h 中做这样的事情:

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

或者,如果您不确定 typedef 的确切工作原理,只需执行以下操作:

 struct point {
  int row, col;
}

这声明了一个结构类型。

于 2012-11-01T17:49:38.230 回答