求助解决C语言中int str_find(char*, char*)重定义错误
修复"redefinition of 'int str_find(char*, char*)'"错误
错误根源
- 头文件中直接编写函数实现:
my_functions.h里的str_find是完整的函数定义(带函数体),且放在了头文件保护宏#endif之外,只要包含该头文件就会引入一次函数定义。 - 主文件同时包含
.c和.h文件:主代码里#include "my_functions.c"会将整个.c文件内容插入,而my_functions.c又包含了my_functions.h,加上主文件自身也包含该头文件,最终导致str_find的定义被多次编译,触发重复定义错误。
具体修复步骤
步骤1:修正my_functions.h,仅保留函数声明
头文件只负责声明函数接口,把所有函数实现移到.c文件,且确保所有内容都在头文件保护宏内部:
#ifndef MyFunctions_h #define MyFunctions_h #include <stdio.h> // 仅保留函数声明,不要实现 void str_copy(char *destination, char *source); int str_length(char *mystring); int str_find(char *needle, char *haystack); #endif
步骤2:将函数实现移到my_functions.c
把str_copy和str_find的实现从my_functions.h迁移到my_functions.c中,最终文件内容如下:
#include <stdio.h> #include "my_functions.h" int str_length(char *mystring) { int i = 0; while (*mystring != '\0') { i++; mystring++; } return i; } void str_copy(char *destination, char *source) { while (*source != '\0') { *destination = *source; source++; destination++; } *destination = '\0'; } int str_find(char *needle, char *haystack) { int i = 0; int c = 0; while (*needle != '\0') { ++i; ++needle; } needle -= i; while (*haystack != '\0') { ++c; ++haystack; } haystack -= c; int k = 0; int sp = 0; for (int d = 0; d <= c; ++d, ++haystack) { if (*haystack == *needle && k == 0) { sp = d; ++k; ++needle; } else if (*haystack != *needle && k != 0) { needle -= k; k = 0; } } if (sp == 0) { return -1; } else { return sp; } }
步骤3:修改主文件,仅包含头文件
主文件无需包含.c文件,只需要引入对应的头文件即可,顺便修正主函数参数名写反的问题(标准写法是argc为参数个数,argv为参数数组):
#include <stdio.h> #include "my_functions.h" int main(int argc, char **argv) { for (int i = 0; i < argc; i++) printf("%s\n", argv[i]); printf("%d\n", str_find("=", "-h=123")); printf("%d\n", str_find("xyx", "aaaa")); return 0; }
步骤4:编译时链接所有源文件
在VS Code中编译时,要将主文件和my_functions.c一起编译,比如使用gcc命令:
gcc main.c my_functions.c -o program
编译完成后运行./program即可执行程序。
内容的提问来源于stack exchange,提问作者onix012
相关产品推荐
相关产品推荐

