C函数没有头文件

M.K*_*.K. 14 c header-files

这应该是非常微不足道的.我正在运行一个非常基本的C程序来比较字符串:

#include <stdio.h>  
int strcmp(char *s, char *t);
int main()
{
    printf("Returned: %d\n", strcmp("abc", "adf"));
    return 0;
}

int strcmp(char *s, char *t)
{
    printf("Blah\n");
    while (*s++ == *t++)
    {
        if (*s == '\0')
            return 0;
    }
    return *s - *t;
}
Run Code Online (Sandbox Code Playgroud)

所以我基本上实现了我自己的string.h中已经存在的strcmp函数版本.当我运行上面的代码时,我只看到返回值0,1或-1(至少对于我的一小组测试用例)而不是实际的预期结果.现在我意识到这是因为代码不是我的strcmp的实现版本,而是使用函数的string.h版本,但我很困惑,为什么会出现这种情况,即使我没有' t包括适当的头文件.

另外,看看它是如何使用头文件版本的,在编译代码时,我不应该得到"多个实现"错误(或者这些行中的某些内容)吗?

mu *_*ort 14

你正在使用gcc,对吧?gcc在编译器中将一些函数实现为内置函数,它似乎strcmp就是其中之一.尝试使用-fno-builtin开关编译文件.

头文件只告诉编译器存在某些符号,宏和类型.包含或不包含头文件不会对函数的来源产生任何影响,这是链接器的工作.如果gcc strcmp退出libc,你可能会看到一个警告.


hac*_*rks 6

不像以前的答案那样优雅,另一种方法可以完成

#include <stdio.h>  
static int strcmp(char *s, char *t); /* static makes it bind to file local sym */
int main()
{
    printf("Returned: %d\n", strcmp("abc", "adf"));
    return 0;
}

int strcmp(char *s, char *t)
{
    printf("Blah\n");
    while (*s++ == *t++)
    {
        if (*s == '\0')
            return 0;
    }
    return *s - *t;
}
Run Code Online (Sandbox Code Playgroud)