Working on computing the geometric mean of values in an array
The function should compute the geo mean correctly, but i'm getting a weird error message
#include <stdio.h>
#include <stdint.h>
#include <math.h>
extern "C"
double geomean(double myarray[], int count) ////error here, expected '(' before string constant
{
double geomean = 1;
double root = (1/(double)count);
int i;
for(i = 0; i < count; i++)
{
geomean = geomean * myarray[i];
}
geomean = pow(geomean, root);
return geomean;
}
extern "C"
is not valid C (it's only valid in C++). Just remove it if you're working in pure C.
I am answering this question in an attempt to cover that could have been covered in more detailed answer to aid the questioner or other persons visiting this page.
Error: “expected '(' before string constant”
As mentioned in some other answer of your question, extern "C"
is not valid C (it's only valid in C++). You can remove it if you're using only pure C.
However, if you (or someone else) have a mix of C and C++ source files, then you can make use of macro __cplusplus
. __cplusplus
macro will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file.
Thus, the same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C" when being interpreted as C++, and they should not have extern "C" when being interpreted as C (as in your case you were getting an error!).
#ifdef __cplusplus
extern "C" {
#endif
// Your prototype or Definition
#ifdef __cplusplus
}
#endif
Note: All
extern "C"
does is affect linkage. C++ functions, when compiled, have their names mangled. This is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must
extern "C"
the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic when you were looking for void h(int, char)
).
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