C项目文件错误: structure is being duplicated in 2 files

标签 c project

我有一个 C 语言项目文件,其中在 file.H 中声明了一个结构,并且 2 个文件包含 file.h,
.H文件的内容:

#ifndef SORT_H
#define SORT_H

struct lnode {
 int data;
 struct lnode *next;
} *head, *visit;

void add(struct lnode **q, int num);


/*typedef struct lnode NODE; */



#endif

++++ ADD.C+++++ 的内容

#include "SORT.H"

void add(struct lnode **q, int num)
{
     struct lnode *temp;

     temp = *q;

     /* if the list is empty, create first node */
     if(*q == "") {
      *q = malloc(sizeof(struct lnode));
       temp = *q;
     } else {
      /* go to last node */
      while(temp->next != "")
       temp = temp->next;

       /* add node at the end */
       temp->next = malloc(sizeof(struct lnode));
       temp = temp->next;
     }

     /* assign data to the last node */
     temp->data = num;
     temp->next = "";
}

++++ SORT.C++++ 的内容

#include "SORT.h"
#include<conio.h>
#include<stdio.h>

void main(){

    struct lnode *newnode = NULL;
    char choice;
    int lim, i = 0, num;

    clrscr();

     /*get max value*/
     printf("Input no. of values: ");
     scanf("%d",&lim);

     for(i = 0; i <= lim; i++){
        printf("[%i] = ",i);
        scanf("%d",&num);
        add(&newnode, num);
     }


    head = newnode;
    for(;;){
        printf("\n\n\nMENU: \n");
        printf("[A]Selection Sort\n[B]Insertion Sort\n[C]Exchange Sort\nChoice: ");
        scanf("%s",&choice);

        switch(toupper(choice)){
            case 'A':
                      clrscr();
                      printf("Selection Sort: \n");
                      break;
            case 'B':
                      clrscr();
                     printf("Insertion Sort: \n");

                      break;
            case 'C':
                      clrscr();
                        printf("Exchange Sort: \n");
                      break;
            case 'D':
                      exit();
                      break;
            default:
                      clrscr();
                      printf("Incorrect choice!\n\n\n");
                      break;
        }
    }
}

我收到链接器错误:_head 和 _visit 正在从 file1.c 复制到 file2.c。

我的 2 个文件中需要这个结构,无论如何我都要这样做,如果您需要更多信息,请直接说出来。

最佳答案

变量 headvisit 被定义为头文件中的全局变量,头文件包含在两个文件中。因此它们是双重定义的。您需要在 header 中声明这些变量并在 .c 文件之一中定义它们。

#ifndef SORT_H
#define SORT_H

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

extern struct lnode  *head, *visit;
...
#endif

在 SORT.C 中

struct lnode  *head, *visit;

关于C项目文件错误: structure is being duplicated in 2 files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21072592/

相关文章:

c - 具有线性探测的哈希表

search - 将 Emacs 用于大型项目

xcode - 在我的项目之外创建 NSManagedObjectSubclasses 生成类

git - 您如何管理项目中的第三人称 git 存储库? (例如 Twig/Assetic/..)

c - 在头文件中声明一个字符串返回函数。冲突的类型?

C: Julian day library - 如何从日期偏移量(自 X 以来的天数)获取日期(即 yyyy/mm/dd)?

cdev初始化为linux设备驱动: what is the difference between the two approaces?

maven - 在 intellij 中搜索 Maven 原型(prototype)列表

java - 循环依赖或构建项目的正确方法

C编程退出不工作