我有一个 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 个文件中需要这个结构,无论如何我都要这样做,如果您需要更多信息,请直接说出来。
最佳答案
变量 head
和 visit
被定义为头文件中的全局变量,头文件包含在两个文件中。因此它们是双重定义的。您需要在 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/