I have a question about Preprocessor directives in C and C++.
I have the following code:
#ifdef __cplusplus
//part A
extern "C"
{
// somecode here
}
#else
//part B
#endif
I know the c++ complier predefined the __cplusplus will c compiler does not.
And I put this set of code into a c header file, and c++ file will include this c header file. And my question is: if the file is compiled by a c++ compiler, it will compile the part A, and if it is compiled by a c compiler, it will compile the part B, but normally, we use this code to make c++ file and c file interact with each other, if we have such code above, I mean we have both C and C++ file together, and we use gcc compiler, how this code is compiled? only part A is compiled? or only part B is compiled? or the code is devided into two parts, part A is compiled for C++ and part B is compiled for C file at the same time?
In a project with multiple source files, the header is not processed just once by the compiler.
When the compiler compiles a C++ file, it reads that file and any headers it includes (directly or indirectly) and processes the contents of those files using the rules for C++.
When the compiler compiles a C file, it reads that file and any headers it includes (directly or indirectly) and processes the contents of those files using the rules for C.
The result will be as if the code in your header file appeared separately in the C++ source and in the C source.