如何为链表功能创建库

时间:2017-06-06 08:29:24

标签: c struct static-libraries

我想为链表功能创建静态或动态库,但是当我尝试使用gcc编译函数文件来获取目标文件时,它会给我错误‘struct node’ declared inside parameter list int GetNth(struct node* head, int index)& dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;。不知道发生了什么,可能是因为我还没有在文件中声明structure

#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}

但如果我在这个文件中声明它,我认为它违反了1个定义规则。怎么办?
结构在main函数中声明为

struct node{
  int data;
  struct node *next;
}

3 个答案:

答案 0 :(得分:1)

在使用对象之前(使用它,当有权访问其成员时),您必须完全定义它们。因此,要使用struct node,请在源代码中首次出现之前声明它。它是C编程语言的规则。

如果要创建有用的库,请将声明放入头文件并将文件包含到源文件中,例如:

...
struct node
{
    ...
};

int count(struct node *head, int n);
...

答案 1 :(得分:0)

编译器告诉您它无法识别struct node。你需要先声明它。类似struct node; decleration )或struct node{...}; definition )之类的内容,错误应该消失。如果您已在另一个文件header.h中声明了它,只需在代码的开头添加#include "header.h"

由于您希望struct node包含名为data的字段,因此您需要在定义结构时添加它:

struct node{
    int data;
}

答案 2 :(得分:0)

继续注释,在您的代码中,编译器不知道node是什么,因为您没有提供其声明。为方便起见,您可以提供包含typedef的声明。以下代码将typedef struct _node {...}声明为node;,然后声明两个节点(出于简单原因静态),迭代列表,输出data值,然后结束,例如

#include <stdio.h>

typedef struct _node {
    int data;
    struct _node *next;
} node;

int main (void) {

    node n1 = {.data = 1}, 
         n2 = {.data = 2, .next = NULL};
    n1.next = &n2;

    /* iterate over list outputting data values */
    for (node *n = &n1; n != NULL; n = n->next)
        printf ("%d\n", n->data);

    return 0;
}

示例使用/输出

$ ./bin/llstatic
1
2

如上所述,您可以为列表创建一个头文件,并在其中包含struct _nodetypedef的声明,或者如果您只是在此源文件中使用node,你可以在这里声明。如果您还有其他问题,请与我们联系。