Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementation of C header files?

I was learning the C language and was peeking through some header files in the Linux directory /usr/include such as stdio.h, stdlib.h etc. What really was bothering me was that I see all functions define with an extern keyword, which means they are only being declared without any definition such as:

extern FILE *fopen (__const char *__restrict __filename,
                    __const char *__restrict __modes) __wur;

The same goes for every other function in every other header file. My question is, if they are only being declared where are their implementations? They have to be implemented somewhere right?

like image 327
saad Avatar asked Dec 03 '22 08:12

saad


2 Answers

Those are called function prototypes. They tell the compiler that the function exists, but not where (yet). The compiler uses this to make sure that you're calling the function correctly, but that's it.

Once the compiler is done, the linker gets called. This is where the magic happens. The linker determines which library has the actual implementation of the function. In this case it's probably going to be in the standard library (called libc on some systems), which is automatically pulled in. The linker does its thing, and your calls to that function are then handled by the library.

If the prototype exists, but the implementation can't be found, you get a linker error (something along the lines of "undefined symbol"). If the prototype is missing, the code will compile but you'll probably get a warning about it (thanks Jim Balter for the info about this).

like image 156
Chris Eberle Avatar answered Dec 27 '22 05:12

Chris Eberle


Header files only define the interface to the standard library functions, not the implementation; they (as a rule) don't contain any executable code.

It depends on the compiler and platform, but typically the standard library functions have already been compiled and collected into binary files that your code is linked against to produce an executable.

If you're on a Linux system using gcc, you can find these library files under /usr/lib. libc.a typically contains the bulk of the C standard library functions (stdio, stdlib, string, etc.). Math functions are stored separately in libm.a. Under normal circumstances, gcc links against /usr/lib/libc.a automatically, so you don't have to worry about it. If you need to use math library functions, you need to add -lm to the command line to link against the math library.

Note that most implementations do not ship the source code for the library functions themselves; all you get is the precompiled binary files.

like image 37
John Bode Avatar answered Dec 27 '22 05:12

John Bode