为什么我不能在VC6.0中使用#include "getline.c"
或strindex.c
?
-----test30src.c------
#include <stdio.h>
#include "getline.c"
#include "strindex.c"
#define MAXLINE 1000
char pattern[] = "ould";
int main()
{
char line[MAXLINE];
int found = 0;
while(getline(line, MAXLINE) > 0)
if(strindex(line, pattern) >= 0){
printf("%s", line);
found++;
}
return found;
}
------getline.c------
#include <stdio.h>
int getline(char s[], int lim)
{
int c, i;
i = 0;
while(--lim > 0 && (c = getchar()) != EOF && c != '\n')
s[i++] = c;
if(c=='\n')
s[i++] = c;
s[i] = '\0';
return i;
}
-----strindex.c-----
int strindex(char s[], char t[])
{
int i, j, k;
for(i = 0; s[i] != '\0'; i++){
for(j = i, k = 0; s[j] == t[k]; j++, k++)
;
if(k > 0 && t[k] == '\0')
return j;
}
return -1;
}
错误:
--------------------Configuration: test30 - Win32 Debug--------------------
Linking...
getline.obj : error LNK2005: _getline already defined in test30src.obj
strindex.obj : error LNK2005: _strindex already defined in test30src.obj
Debug/test30.exe : fatal error LNK1169: one or more multiply defined symbols found
发布于 2014-01-23 09:29:24
您应该包含string.h .h,而不是getline.c
发布于 2014-01-23 09:39:11
不能包含包含定义的文件,否则最终会出现相同函数的多个实例。创建只包含声明的头文件。
getline.c (定义)
#include "getline.h"
int getline(char s[], int lim) { ... }
getline.h (仅限声明)
#ifndef GETLINE_H
#define GETLINE_H
int getline(char s[], int lim);
#endif
main.c (仅包含标头)
#include "getline.h"
发布于 2014-01-23 09:39:53
默认情况下,大多数IDE将编译所有.c文件。在这里,它将编译一次getline.c
和strindex.c
,并在编译testsrc30.c
时进行第二次编译,其中包括另外两个文件。请记住,#include
指令只是复制所包含文件的内容。
在链接时,一些符号被发现两次,链接器无法处理歧义-
使用#include
的标准方法是使用包含函数声明的头文件(.h)。
示例
//getline.h
#ifndef GETLINE_H //Header guard - avoid multiple inclusion
#define GETLINE_H
#include <stdio.h>
int getline(char s[], int lim); //function declaration
#endif // GETLINE_H
。
//getline.c
#include "getline.h"
int getline(char s[], int lim) //declaration
{
// Implement whatever your function does
}
。
// test30src.c
#include "getline.h"
int main(void)
{
// Put your code here
}
在某些情况下,包含.c文件可能是可以接受的。但在这种情况下,您应该确保这些.c文件不会自行编译和链接。请参阅此相关问题:Including one C source file in another?
https://stackoverflow.com/questions/21304099
复制