我已经在线查看,无法获得完全正确的语法。我正在尝试创建一个头文件,以便我可以在另一个C源文件中使用一个函数。该功能被称为readLine()
,它位于myown.c
。我想在myown3.c
中使用它。如何使用头文件创建简单的C库
这里是头文件myown.h
:
#define LINECAP 81
#ifndef MYOWN_H
#define MYOWN_H
void readLine (char buffer [], LINECAP);
#endif
这里是myown.c
#include "myown.h"
#include <stdio.h>
void readLine (char buffer [], int lineCapacity) {
char myCharacter;
int i = 0 ;
do {
myCharacter = getchar();
buffer[i] = myCharacter;
i++;
} while (myCharacter != '\n' && i < lineCapacity);
buffer [i-1] = '\0';
}
void cleanBuffer (char buffer []) {
int i;
for (i=0; i<81; i++)
buffer[i] =0;
}
int main (int argc, char *argv[]) {
/* void readLine (char buffer [], int lineCapactiy); */
void cleanBuffer(char buffer []);
int i;
char line[81];
for (i=0; i<3; i++) {
//cleanBuffer(line);
readLine(line,LINECAP);
printf("%s", line);
//cleanBuffer(line);
}
}
这里是myown3.c
,我想使用的功能:
#include "myown.h"
#include <stdio.h>
#include <stdbool.h>
bool alphabetic (const char c) {
//if ((c > 65 && c < 90) || (c > 97 && c < 122))
if ((c > 'a' && c < 'z') || (c > 'A' && c < 'Z'))
return true;
else
return false;
}
int countWords (const char string[]) {
int i, wordCount =0;
bool lookingForWord= true, alphabetic (const char c);
for (i = 0; string[i] != '\0'; ++i) {
if (alphabetic(string[i])) {
wordCount++;
lookingForWord = false;
} else {
lookingForWord = true;
}
}
return wordCount;
}
int main (int argc, char *argv[]) {
char text[81];
int totalWords =0;
int countWords (const char string[]);
/* void readLine (char buffer[], int lineCapacity); */
bool endOfText = false;
printf ("Type in your text.\n");
printf ("Wehn you are done, press 'RETURN'.\n");
while (! endOfText) {
readLine (text, 81);
if (text[0] == '\0')
endOfText = true;
else
totalWords == countWords (text);
}
printf ("\nThere are %i words in the above text.\n", totalWords);
return 0;
}
我尝试编译时出现以下错误:
gcc -I. myown.c -o myown
In file included from myown.c:1:0:
myown.h:1:17: error: expected declaration specifiers or '...' before numeric constant
#define LINECAP 81
^
myown.h:4:33: note: in expansion of macro 'LINECAP'
void readLine (char buffer [], LINECAP);
^
make: *** [myown] Error 1
一切正常。我花了一些时间才弄清楚我必须单独编译和链接这些部分。我得到了以下错误,当我试图一下子编译事情:
$ gcc -I. myown3.c -o myown3
C:\Users\sansari\AppData\Local\Temp\ccYfmI6U.o:myown3.c:(.text+0xd1): undefined reference to `readLine'
collect2.exe: error: ld returned 1 exit status
但下面的命令工作....
gcc myown.c -c -o myown.o
gcc myown3.c -c -o myown3.o
gcc myown3.o myown.o -o myown3
什么是'readLine'应该是第二个参数? – fuz
在旁边注意,您可以使用标准库的东西来做类似于alphanum check的事情,例如'字符isalnum(字符)'。检查'ctype.h'获取更多内容。 –
2一般性评论,首先,你需要在头文件中包含保护的#define。有助于避免重新宣布的警告。其次,你在你的函数原型中使用了一个常数,它与你的函数定义有所不同。你会想改变原型来匹配(使用'int')。 – engineer14