Alec Bender
Alec Bender

Reputation: 51

Inclusion of C headers in C++ revisited

I just read a question on SO discussing scenarios in which a piece of code is valid in both C and C++ but would produce different behavior in each language.

This begs the question: Could this ever be a problem when including C headers in C++ code?

I know from this question that you should include C headers like this:

extern "C" {
#include <your_os_or_library_header_in_c.h>
}

But all I found so far is that the extern "C" only guarantees that name mangling is turned off.

I couldn't find any information on whether it evaluates all statements as C, so that e.g. sizeof('a') or 10 //* comment */ 2 (which you could find in an inline function) are parsed as C and not C++. (Note that relying on such behavior as someone who writes a C header is obviously a bad idea, but I'm asking it from a purely academic standpoint of "What if?".)

Does the C++ standard say that enclosing a block of code in extern "C" means that all statements in it must be parsed as C?

Upvotes: 5

Views: 449

Answers (2)

Fred Foo
Fred Foo

Reputation: 363617

extern "C" only changes linking, i.e. mangling and possibly the calling convention. Try compiling and running this program with both a C and a C++ compiler:

#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif
    inline void putsizeofchar()
    {
        printf("%zd\n", sizeof(char));
    }
#ifdef __cplusplus
}
#endif

int main()
{
    putsizeofchar();
    return 0;
}

Since header inclusion is textual substitution in both languages, the lack of a header doesn't make any difference.

Upvotes: 3

extern "C" is a C++ construct which affects language linkage in a C++ program. It does not switch the language to C in any way. All source text inside an extern "C" declaration is still parsed as C++ and as C++ only.

Note that extern "C" affects more than just name mangling - it is (theoretically) possible that functions with C and C++ language linkage could have different calling conventions, for example.

Upvotes: 7

Related Questions