Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C functions without header files

Tags:

c

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 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?

like image 582
M.K. Avatar asked May 08 '11 06:05

M.K.


People also ask

Can C program run without header file?

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.

Do all C files need a header file?

No, it is not necessary. The reason of the header files is to separate the interface from the implementation.

What happens if header files were not used in C program?

Without a header file, you cannot run or compile your program code. In C, all program codes must include the stdio. h header file.

Why does C require header files?

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.


1 Answers

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.

like image 102
mu is too short Avatar answered Oct 01 '22 02:10

mu is too short