【发布时间】:2013-07-13 15:18:01
【问题描述】:
据说我们可以写多个声明,但只能写一个定义。现在,如果我用相同的原型实现自己的 strcpy 函数:
char * strcpy ( char * destination, const char * source );
那我不是在重新定义现有的库函数吗?这不应该显示错误吗?还是与库函数以目标代码形式提供这一事实有某种关系?
编辑:在我的机器上运行以下代码会显示“分段错误(核心转储)”。我在 linux 上工作并且没有使用任何标志进行编译。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strcpy(char *destination, const char *source);
int main(){
char *s = strcpy("a", "b");
printf("\nThe function ran successfully\n");
return 0;
}
char *strcpy(char *destination, const char *source){
printf("in duplicate function strcpy");
return "a";
}
请注意,我不是在尝试实现该功能。我只是想重新定义一个函数并询问后果。
编辑 2: 应用 Mats 建议的更改后,尽管我仍在重新定义函数,但程序不再给出分段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strcpy(char *destination, const char *source);
int main(){
char *s = strcpy("a", "b");
printf("\nThe function ran successfully\n");
return 0;
}
char *strcpy(char *destination, const char *source){
printf("in duplicate function strcpy");
return "a";
}
【问题讨论】:
-
你不能那样做,那会崩溃
-
@DGomez 在我的机器上,程序没有崩溃。
-
@SabashanRagavan:首先我没有,然后我做了:同样的结果
-
正如我在回答中所说,编译器在看到
strcpy时几乎肯定会内联代码 - 这是“你不能用相同的名称编写自己的函数”的动机之一作为库函数”。
标签: c