Error: “expected '(' before string constant”

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

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  #include  #include    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 

回答1:

extern "C" is not valid C (it's only valid in C++). Just remove it if you're working in pure C.



回答2:

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)).



回答3:

the first line should be: extern C;

The other option would be declaring c outside the main function without the extern keyword...



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!