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?
You can #include them using their original names. #include <stdio. h> works just fine in C++. The C standard headers are required to work in standard C++, although you may be putting more than you like into the global namespace.
If your file does not include its own header, you can accidentally get in a situation when forward declaration of a function does not match the definition of the function - perhaps because you added or removed a parameter, and forgot to update the header.
A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
Header files serve two purposes. System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With