cong
cong

Reputation: 1187

Why could c++ include <stdio.h> and invoke printf method which is c(platform:ubuntu 14.04 compiler:gcc 4.8.4)

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

#include <stdio.h>
int main() {
    printf("test...\n");
    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)

Upvotes: 1

Views: 617

Answers (4)

Sam Varshavchik
Sam Varshavchik

Reputation: 118350

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>

__BEGIN_DECLS

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    }
#else
# define __BEGIN_DECLS
# define __END_DECLS
#endif

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".

Upvotes: -1

Brian Bi
Brian Bi

Reputation: 119219

Nobody can give you a definitive answer without knowing what implementation you're using.

Cheers and hth. - Alf gave one possibility, which is that the stdio.h that is included by a C++ program may not be the same as the stdio.h that is included by a C program. Another possibility is that it is the same header, and there is an extern "C" block, and you just can't see it. For example, I use gcc, and my /usr/include/stdio.h contains a __BEGIN_DECLS macro, which expands to extern "C" { when compiled as C++. See Do I need an extern "C" block to include standard C headers?

Upvotes: 1

Nonanon
Nonanon

Reputation: 560

When C++ was originally made it was effectively a superset of C. That is to say, you can code perfectly good C in the C++ environment, just by ignoring all of the features that C++ adds. That, and because nowadays most C compilers are C++ compilers in which you can code C, is why you can use printf.

Secondly, no object code is generated for stdio because it is already a library, and so you are linking your own .o code against the already compiled stdio library code, which will be located somewhere in your compilers directory.

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

printf is part of the C++ standard library.

The <stdio.h> header that you include in the C++ source, belongs to the C++ standard library, and is not necessarily the same contents as a C compiler will include.

How the C++ implementation leverages the corresponding C implementation (if at all) is an implementation detail.

Upvotes: 3

Related Questions