I failed to define overloading functions with error message of error: conflicting declaration of C function
if enclosing by #ifdef __cplusplus
blocks.
Below is a simple code for an easy view. This piece of code worked fine without #ifdef __cplusplus
blocks.
However, my project code does need #ifdef __cplusplus
as it involves combination of C and C codes.
Command lines after #ifdef __cplusplus
block should be C , why did it fail to define the overloading function? How to fix this problem with presence of #ifdef __cplusplus
blocks?
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
int add(int x)
{
return x;
}
int add(int x, int y)
{
return x y;
}
int main() {
// cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
int X = add(2);
int Z = add(8,2);
cout <<X<<" "<<Z<<endl;
return 0;
}
#ifdef __cplusplus
}
#endif
CodePudding user response:
Command lines after #ifdef __cplusplus block should be C
First of all, I believe you have a misconception of #ifdef __cplusplus
, this macro only checks if your compiler is a C compiler or not.
You rather need focus on extern "C" {}
. This block of code explicitly tells your compiler, that codes inside this block must be in C language(not C ).
This is important since C and C have different mechanisms of storing and calling functions from binary. (Called name mangling). Better to say, C and C binaries are not compatible. So extern "C"
will tell your compiler that your functions C codes, and those function names are not mangled.
So #ifdef __cplusplus
checks if your code is C or C ; if your code is in C , insert extern "C" {
that tells your compiler that those codes in this block are C code.
And since function overloading is not a part of C language, your compiler will cause an error inside that block. (This matters with name mangling).
But this macro is mostly used in header files, not source files. Because the purpose of this macro is to enable your code to be included in both C and C code, but source files cannot be and must not be included by another source.