Without including <stdio.h>

Does this program work without inclusion below <stdio.h>? Why does it work?

int main()
{
    printf("integra");
    return 0;
}
+5
source share
6 answers

The definition of printf () is in libc.so, and the dynamic linker will take care of this even if you do not include the header file. At compile time, printf () will be an undefined character and assumes that it can find the definition later in libc. The header file will simply give a prototype and suppress the compiler (warnings), which states that the prototype definition is present in glibc. Thus, basically the header files are included just to make sure that the definitions are available in our libraries to help the developer.

+8
source

, int . char* (32-) int, .

.

+7

printf() libc.so

printf() libc,

libc gcc

+5

, , stdio.h, std undefined (printf). GCC .

test.c:

1: int main()
2: {
3:    printf("test\n");
4:    return 0;
5: }

test.c GCC 4.2.1 Mac OSX:

$ gcc test.c
test.c: In function ‘main’:
test.c:3: warning: incompatible implicit declaration of built-in functionprintf
$ ./a.out
test

, GCC -nostdlib ( -nodefaultlibs) -lgcc ( GCC):

$ gcc -nostdlib -lgcc test.c
test.c: In function ‘main’:
test.c:3: warning: incompatible implicit declaration of built-in functionprintf
Undefined symbols:
  "_puts", referenced from:
      _main in cc3bvzuM.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
$
+3

(?) .

+1

, , , int , .

If this assumption matches the definition of the function, and if the arguments you provide also match (modulo the default arguments advanced) the parameters that the function expects to receive, then everything will be fine. If the assumption is incorrect (for example, for printf, which is a variational function) or when the arguments do not match, the results are undefined. One of the unpleasant things about undefined behavior is that it can work as expected.

+1
source

All Articles