project1.h
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct list
{
char name[20];
char value[20];
struct list *next;
};
struct list *head = NULL; //全局变量
void Printlist();
char zhuanhua(char p);
struct list *comment(char *filename);
project1.c
#include"project1.h"
struct list *comment(char *filename) //函数定义
{
char name[20], value[20];
char str[256];
char *p1, *p2;
struct list *p = NULL, q = NULL;
FILE fp;
fp = fopen(filename,“r”); //读,打开文件
if(NULL == fp)
{
printf(“can’t open file\n”);
}
p = (struct list)malloc(sizeof(struct list));
head = p;
while(!feof(fp)) //判断是否到结尾
{
fgets(str, 256, fp);
if(strlen(str) <= 2)
{
continue;
}
//printf( “str = %s\n”, str );
if((p1 = strchr(str, ‘#’)) != NULL)
{
p1 = ‘\0’; //去除注释
}
else
{
p1 = str;
/ printf( “…str = %p\n”, str );
printf( “…>>str的长度 = %d\n”, strlen(str) );/
(p1+strlen(str)+1) = ‘\0’;
}
if((p1 = strchr(str, ‘=’)) != NULL)
{
p2 = p1 + 1;
p1 = ‘\0’; //等号两边分离
}
else
{
printf(“Input error\n”);
continue;
}
q = (struct list)malloc(sizeof(struct list)); //创建链表
//printf("%s%s\n", zhuanhua(str), zhuanhua(p2));
strcpy(q->name,zhuanhua(str));
strcpy(q->value,zhuanhua(p2));
//printf("%d…=",strlen(q->value));
p->next = q;
p = q;
//printf(“p->name =%s\t\t\tp->value =%s\n”,p->name, p->value);
//exit(1);
}
fclose(fp);
return head;
}
char zhuanhua(char p) //去空格
{
int i, j;
char p1;
int n = strlen§;
for (i = 0; i < n; i++) //对字符串开头中第一个字符定位
{
if ((p+i) != ’ ')
{
p1 = p+i;
break;
}
}
for (j = n-1; j >= 0; j–) //对字符串的最后一个字符定位
{
if ((p+j) != ’ ')
{
*(p+j+1) = ‘\0’;
break;
}
}
return p1;
}
void Printlist() //打印链表
{
struct list *p = NULL;
p = head->next;
while§
{
printf("<%s><%s>\n", p->name, p->value);
p = p->next;
}
}
main.c
#include"project1.h"
void main()
{
struct list *p;
p = comment(“file.txt”);
Printlist();
}
用makefile编译运行时出现错误
gcc -o Hello project1.o main.o
main.o:(.bss+0x0): head 的多重定义
project1.o:(.bss+0x0):第一次在此定义
collect2: 错误:ld 返回 1
make: *** [Hello] 错误 1