C functions without header files
This should be very trivial. I was running through a very basic C program for comparing strings:
#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;
}
So I've basically implemented my own version of the strcmp function already present in string.h. When I run the above code, I only see return values of 0, 1, or -1 (at least for my small set of test cases) instead of the actual expected results. Now I do realize that this is because the code doesn't go to my implemented version of strcmp, but instead uses the string.h version of the function, but I'm confused as to why this is the case even when I 开发者_StackOverflow社区haven't included the appropriate header file.
Also, seeing how it does use the header file version, shouldn't I be getting a 'multiple implementations' error (or something along those lines) when compiling the code?
You're using gcc, right? gcc implements some functions as built-ins in the compiler and it seems that strcmp
is one of those. Try compiling your file with the -fno-builtin
switch.
Header files just tell the compiler that certain symbols, macros, and types exist. Including or not including a header file won't have any effect on where functions come from, that's the linker's job. If gcc was pulling strcmp
out of libc then you probably would see a warning.
Not as elegant as the earlier answers, another way to get this done
#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;
}
Without knowing what compiler and lib. version you use, all conclusion are only 'possibility'. So the most reasonable thing that stdio.h
already includes stdlib.h
or string.h
strcmp
is the name of a standard library function. As such you are only permitted to declare the function (although you must use a correct declaration); you are not permitted to provide another definition for it. The implementation can assume that whenever you use strcmp
you are referring to the standard library function even if you haven't used the correct #include
for it.
If you want to provide an alternative strcmp
then you should give it an alternative name.
精彩评论