关于头文件的问题。一定给分!
我是C++的一名初学者。最近看《C++编程思想(Thinking in C++)》(机械工业出版社),里面有几个练习程序,我依原样输入源码,但是编译出错。其中有一个程序是这样的:
//lib.h文件
/*: LIB.H -- Header file:example C library */
/* Array-like entity created at run-time */
typedef struct STASHtag {
int size; /* Size of each space */
int quantity; /* Number of storage spaces */
int next; /* Next empty space */
unsigned char* storage;
} Stash;
void initialize(Sash* S, int Size);
void cleanup(Stash* S);
int add(Stash* S,void* element);
void* fetch(Stash* S,int index);
int count(Stash* S);
void inflate(Stash* S,int incease);
// end of lib.h
//lib.c
/*:LIB.C -- implementation of example C library */
/* Declare structure and functions: */
#include "..\1\lib.h"
/* Error testing macros: */
#include <assert.h>
/* Dynamic memory alloction functions: */
#include<stdlib.h>
#include<string.h> /* memcpy() */
#include<stdio.h>
void initialize(Stash* S,int Size) {
S->size=Size;
S->quantity=0;
S->storage=0;
S->next=0;
}
void cleanup(Stash* S) {
if(S->storage) {
puts("freeing storage");
free(S->storage);
}
}
int add(Stash* S, void* element) {
/* enough space left? */
if(S->next >= S->quantity)
inflate(S,100);
/* Copy element into storage, starting at next empty space: */
memcpy(&(S->storage[S->next * S->size]),element, S->size);
S->next++;
return (S->next - 1); /* Index number */
}
void* fetch(Stash* S,int index) {
if(index >= S->next || index < 0)
return 0; /* Not out of bounds? */
/* Produce pointer to desired element: */
return (&(S->storage[index*S->size]);
}
int count(Stash* S) {
/* Number of elements in stash */
return S->next;
}
void inflate(Stash* S,int increase) {
void* V=realloc(S->storage, (S->quantity + increase) * S->size);
/* Was it successful? */
assert(v);
S->storage = v;
S->quantity += increase;
}
// end of lib.c
// libtestc.c
/*: LIBTESTC.C -- Test demonstration library */
#include "..\1\lib.h"
#include <stdio.h>
#include <assert.h>
#define BUFSIZE 80
main() {
Stash intStash, stringStash;
int i;
FILE* file;
char buf[BUFSIZE];
char* cp;
/* .... */
initialize(&intStash,sizeof(int));
for(i=0;i<100;i++)
add(&intStash,&i);
/* Holds 80-character strings: */
initialize(&stringStash,sizeof(char)*BUFSIZE);
file=fopen("LIBTESTC.C","r");
assert(file);
while(fgets(buf,BUFSIZE,file))
add(&stringStash,buf);
fclose(file);
for(i=0; i <count(&intStash); i++)
printf("fetch(&intStash, %d) = %d\n",i,*(int*)fetch(&intStash,i));
i=0;
while((cp=fetch(&stringStash,i++)!=0)
printf("fetch(&stringStash, %d) = %s", i-1,cp);
putchar('\n');
cleanup(&intStash);
cleanup(&stringStash);
}
// end of libtestc.c
我在编译libtestc.c时,出现编译错误:Stash里面的函数都没定义。我以为原因是因为没有在libtestc.c里包含lib.c文件,于是加进了#include "lib.c",结果出现了重复包含lib.h的错误。(这是我的错误吧?是不是.c文件不可以被包含的?)
后来我把lib.c里的函数定义部分复制到libtestc.c里,结果成功编译、运行。
但是书中很多程序都是这么写的(头文件里声明函数,然后在另一个.c文件里定义函数),应该没有错误。那么我的错误到底中哪里呢?应该怎么样把第三个文件(libtestc.c)与第二个文件(lib.c)联系起来呢?
请各位高手不吝赐教!一定给分!