cong cong - 4 years ago 124
C Question

Why could c++ include <stdio.h> and invoke printf method which is c

c++ compiler could compile code like this, and it executed correctly

#include <stdio.h>
int main() {
return 0;

I think printf.c will be compiled to printf.o with c compiler, I just checked the stdio.h, there is no extern "C" keyword, then how could c++ linker link printf in printf.o which is compiled with c compiler?(By the way, my platform is ubuntu 14.04, compiler is gcc 4.8.4)

Answer Source

You may not see an explicit extern "C" in stdio.h, but it is there. It's just hiding.

For example, on Linux, in stdio.h we see this:

#include <features.h>


In <features.h> you will find the following:

# ifndef _SYS_CDEFS_H
#  include <sys/cdefs.h>
# endif

And in <sys/cdefs.h> you finally see:

#ifdef  __cplusplus
# define __BEGIN_DECLS  extern "C" {
# define __END_DECLS    }
# define __BEGIN_DECLS
# define __END_DECLS

So, via a fairly roundabout path, Linux header files have a __BEGIN_DECLS/__END_DECLS wrapper which, when compiled by a C++ compiler, end up wrapping the whole thing inside extern "C".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download