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 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?
Yes you can wirte a program without #include , but it will increase the complexity of the programmer means user have to write down all the functions manually he want to use.It takes a lot of time and careful attention while write long programs.
No, it is not necessary. The reason of the header files is to separate the interface from the implementation.
Without a header file, you cannot run or compile your program code. In C, all program codes must include the stdio. h header file.
Header files are needed to declare functions and variables that are available. You might not have access to the definitions (=the . c files) at all; C supports binary-only distribution of code in libraries.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With