Lime
Lime

Reputation: 13569

Standard functions defined in header files or automatically linked?

When writing a basic c program.

#include <stdio.h>

main(){
  printf("program");
}

Is the definition of printf in "stdio.h" or is the printf function automatically linked?

Upvotes: 0

Views: 260

Answers (3)

Stricto sensu, the compiler and the linker are different things (and I am not sure that the C standard speaks of compilation & linking, it more abstractly speaks of translation and implementation issues).

For instance, on Linux, you often use gcc to translate your hello.c source file, and gcc is a "driving program" which runs the compiler cc1, the assembler as, the linker ld etc.

On Linux, the <stdio.h> header is an ordinary file. Run gcc -v -Wall -H hello.c -o hello to understand what is happening. The -v option asks gcc to show you the actual programs (cc1 and others) that are used. The -Wall flag asks for all warnings (don't ignore them!). The -H flag asks the compiler to show you the header files which are included.

The header file /usr/include/stdio.h is #include-ing itself other headers. At some point, the declaration of printf is seen, and the compiler parses it and adjust its state accordingly.

Later, the gcc command would run the linker ld and ask it to link the standard C library (on my system /usr/lib/x86_64-linux-gnu/libc.so). This library contains the [object] code of printf

I am not sure to understand your question. Reading wikipedia's page about compilers, linkers, linux kernel, system calls should be useful.

You should not want gcc to link automagically your own additional libraries. That would be confusing. (but if you really wanted to do that with GCC, read about GCC specs file)

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126937

Usually, in stdio.h there's only the prototype; the definition should be inside a library that your object module is automatically linked against (the various msvcrt for VC++ on Windows, libcsomething for gcc on Linux).

By the way, it's <stdio.h>, not "stdio.h".

Upvotes: 3

ibid
ibid

Reputation: 3902

Usually they are automatically linked, but the compiler is allowed to implement them as it pleases (even by compiler magic).

The #include is still necessary, because it brings the standard functions into scope.

Upvotes: 2

Related Questions