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)).
the first line should be: extern C;
The other option would be declaring c outside the main function without the extern keyword...
Related
I am trying to learn the use of the extern keyword. As an example I am using the getopt C library function. From my understanding of the extern keyword, it used to indicate to the compiler that a certain variable that has been defined in another file is going to be used. So whenever I am going to be using the getopt variables like opterr, optind, etc, should I(would it be wrong of me to) do this:
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
extern int optopt;
extern int opterr;
extern int optind;
extern char *optarg;
int main(int argc, char **argv) {
/* code using getopt */
}
When I looked at the manpage for getopt(3), I saw these declarations already mentioned under #include <unistd.h>. So I thought that these were declared in that header file but when I looked into the header file itself, there was no such declaration.
So my question is: is there anything wrong with using these statements at the beginning even if for the sake of improving readability for someone who doesn't how getopt works. Also, at the end of the day if the linker is going to resolve references, anyways, is there any reason to use extern at all?
Also, at the end of the day if the linker is going to resolve references, anyways, is there any reason to use extern at all?
The extern keyword can tell the compiler that an unknown symbol is going to be provided by another file.
Consider the situation where we have file1.c with:
int myvariable;
And file2.c with:
#include <stdio.h>
int main() {
myvariable = 10;
printf("myvariable is %d\n", myvariable);
return 0;
}
Attempting to compile this will fail with:
file2.c: In function ‘main’:
file2.c:4:5: error: ‘myvariable’ undeclared (first use in this function)
4 | myvariable=10;
Adding the appropriate extern declaration to file2.c allows us to compile it without errors:
#include <stdio.h>
extern int myvariable;
int main() {
myvariable = 10;
printf("myvariable is %d\n", myvariable);
return 0;
}
Header files can be nested.
unitstd.h includes many other files, the specific declarations you are looking for are in getopt.h,
These statements do not improve readability, they decrease it by adding duplicate garbage code.
A programmer familiar with C but not with getopt function would think these are your custom variables, not part of the standard library, because nothing in the standard library should be redeclared.
The linker is the last step in building the executable.
The external keyword is for the compiler to know the names and types, so it can build code with references for the linker to resolve later.
While it's OK to have more than one declaration for a function or object, as a rule it's best not to redeclare anything declared in a standard library header. It might cause issues if what you declared doesn't exactly match what's in the headers.
Also, just because the man pages say to include unistd.h doesn't necessarily mean the declaration is in that specific file. The declaration in question could be in a file that unistd.h includes. All it means is that including unistd.h will give you the required declaration.
In my main .c file, I have defined NUMBER as:
#define NUMBER '0'
In another .c file2, I have declared it as an "extern int" variable and used it. But while compiling gcc gives the following error message:
/tmp/ccsIkxdR.o: In function `file2':
file2.c:(.text+0xfd): undefined reference to `NUMBER'
collect2: error: ld returned 1 exit status
Please suggest me a way out. Thanks in advance.
When you use #define is defines a macro for the pre-processor. This macro will only be visible in the source file you defined it in. No other source file will see this macro definition, and the pre-processor will not be able to expand the macro for you in the other source file so the compiler sees the symbol NUMBER and it doesn't have a declaration for any such symbol.
To fix this you have two choices:
Put the macro in a header file that you include in both source files.
Define NUMBER as a proper variable instead of a macro, and then have an extern declaration in the other source file.
When you #define something (i.e create a pre-processor macro) in a C file, it works as text replacement, it's not the declaration of a variable. So, when you write #define NUMBER '0' and write extern int NUMBER; later, the compiler converts it to extern int '0'; before compilation, which is quite meaningless and erroneous.
If you want to define a constant and access it from elsewhere, you can write:
const int NUMBER = '0';
and
extern int NUMBER;
Since your NUMBER is of type int, you could declare it as an enumeration constant:
enum { NUMBER = '0' };
You'd have to put that in a header file (.h) and include that header in your compilation unit (.c file).
Here I have two files externdemo1.c and externdemo2.c.In the first file,I have declared and initialized a character array arr at file scope.But I have declared it in the second file externdemo2.c without the extern keyword and made use of it there in the function display(). Here are my confusions arising from it.Please answer these three:
//File No.1--externdemo1.c
#include<stdio.h>
#include "externdemo2.c"
extern int display();
char arr[3]={'3','4','7'};
//extern char arr[3]={'3','4','7'};
//extern int main()
int main()
{
printf("%d",display());
}
//File No.2--externdemo2.c
char arr[3];
int display()
{
return sizeof(arr);
}
1) Why does the program compile fine even though I have declared arr without the extern keyword in externdemo2.c?I had read that the default linkage of functions is external,but I am not sure if that's so even for variables.I only know that global variables have extern storage class.
2) What is the rigorous difference between extern storage class and extern linkage.I badly need a clarification about this.In the first file,where I have defined the array arr,I haven't used the keyword extern, but I know that it has extern storage class by default.But in the second file, isn't there any default extern ,storage class or linkage,about the global variable arr,ie, in externdemo2.c?
3) Check the commented out line in the first file externdemo1.c.Just to test it, I had used the line extern char arr[3]={'3','4','7'};.But it gives the error 'arr' initialized and declared 'extern'.What does this error mean? I have also mentioned a commented line extern int main(),but it works fine without error or warning.So why can we use extern for a function even though a function is extern by default,but not for a variable,like arr here?
Please take some time to bail me out over this.It will clear most of my lingering doubts about the whole extern thing.It will be immense help if you can answer all 3 bits 1),2) and 3). Especially 3) is eating my brains out
Main questions
Basically, because you've included the source of externdemo2.c in the file externdemo1.c.
This is the big question. Because there is no initializer, the line char arr[3]; in externdemo2.c generates a tentative definition of the array arr. When the actual definition with initialization is encountered, the tentative definition is no longer tentative — but neither is it a duplicate definition.
Regarding extern storage class vs extern linkage...Linkage refers to whether a symbol can be seen from outside the source file in which it is defined. A symbol with extern linkage can be accessed by name by other source files in which it is appropriately declared. To the extent it is defined, extern storage class means 'stored outside of the scope of a function', so independent of any function. The variable defined with exern storage class might or might not have extern linkage.
Because it is not defined with the keyword static, the array arr has extern linkage; it is a global variable.
With the commented out line uncommented out, you have two definitions of one array, which is not allowed.
I observe that you must be compiling just externdemo1.c to create a program — the compiler is including the code from externdemo2.c because it is directly included. You can create an object file from externdemo2.c. However, you cannot create a program by linking the object files from both externdemo1.c and externdemo2.c because that would lead to multiple definitions of the function display().
Auxilliary questions
I have placed both files in the [same directory]. If I don't include the second file in the first, then when I compile the first file it gives the error undefined reference to display. Since I have used extern for that function in the first file, isn't the linker supposed to link to it even if I don't include the second file? Or the linker looks for it only in default folders?
There are a couple of confusions here. Let's try dealing with them one at a time.
Linking
The linker (usually launched by the compiler) will link the object files and libraries that are specified on its command line. If you want two object files, call them externdemo1.obj and externdemo2.obj, linked together, you must tell the linker (via the build system in the IDE) that it needs to process both object files — as well as any libraries that it doesn't pick up by default. (The Standard C library, plus the platform-specific extensions, are normally picked up automatically, unless you go out of your way to stop that happening.)
The linker is not obliged to spend any time looking for stray object files that might satisfy references; indeed, it is expected to link only those object files and libraries that it is told to link and not add others at its whim. There are some caveats about libraries (the linker might add some libraries not mentioned on the command line if one of the libraries it is told to link with has references built into it to other libraries), but the linker doesn't add extra object files to the mix.
C++ with template instantiation might be argued to be a bit different, but it is actually following much the same rules.
Source code
You should have a header, externdemo.h, that contains:
#ifndef EXTERNDEMO_H_INCLUDED
#define EXTERNDEMO_H_INCLUDED
extern int display(void);
extern char arr[3]; // Or extern char arr[]; -- but NOT extern char *arr;
#endif /* EXTERNDEMO_H_INCLUDED */
You should then modify the source files to include the header:
//File No.1--externdemo1.c
#include <stdio.h>
#include "externdemo.h"
char arr[3] = { '3', '4', '7' };
int main(void)
{
printf("%d\n", display());
return 0;
}
and:
//File No.2--externdemo2.c
#include "externdemo.h"
int display(void)
{
return sizeof(arr);
}
The only tricky issue here is 'does externdemo2.c really know the size of arr?' The answer is 'Yes' (at least using GCC 4.7.1 on Mac OS X 10.8.3). However, if the extern declaration in the header did not include the size (extern char arr[];), you would get compilation errors such as:
externdemo2.c: In function ‘display’:
externdemo2.c:7:18: error: invalid application of ‘sizeof’ to incomplete type ‘char[]’
externdemo2.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
Your program looks a bit err. To me the #include "externdemo2.c" line appears invalid.
Following is the correction I have made and it works.
//File No.1--externdemo1.c
#include <stdio.h>
extern char arr[3];
extern int display();
int main()
{
printf("%d", arr[0]);
printf("%d",display());
}
//File No.2--externdemo2.c
char arr[3]={'3','4','7'};
int display()
{
return sizeof(arr);
}
Please follow the below links for better understanding:
Effects of the extern keyword on C functions
How do I use extern to share variables between source files?
Using #include as shown will make both as one file only. You can check the intermediate file with flag -E, as in:
gcc -E externdemo1.c
In some Bison code, what does the following line mean?
#define YY_DECL extern "C" int yylex();
I know #define command but I don't understand the whole command.
It means that YY_DECL will be expanded to
extern "C" int yylex();
This is actually C++, not C; when you compile this file with a C++ compiler, it declares that the function yylex must be compiled with "C linkage", so that C functions can call it without trouble.
If you don't program in C++, this is largely irrelevant to you, but you may encounter similar declarations in C header files for libraries that try to be compatible with C++. C and C++ can be mixed in a single program, but it requires such declarations for function to nicely work together.
There's probably an #ifdef __cplusplus around this #define; that's a special macro used to indicate compilation by a C++ compiler.
#define YY_DECL extern "C" int yylex();
Define a macro YY_DECL standing for the declaration of a function yylex that has 'C' linkage inside a C++ program, taking no arguments and returning an int.
#define - a preprocessor directive declaring a new variable for the preprocessor. But you know that.
YY_DECL - the name of the variable.
extern "C" - tells the compiler that the following code is pure C. There are a lot of differences between C and C++ and one cannot generally mix C and C++ code. If you include this into declaration, it allows you to use C in C++. EDIT: The code actually not need to be pure C, but it will be linked as such. But the most common usage pattern is to make a C code compatible with C++. Thanks #larsmans for the correction.
int yylex() - a declaration of a function named yylex with undefined number of parameters and return type int
So the whole command assigns a C function declaration to a preprocessor variable.
I have two C files and one header that are as follows:
Header file header.h:
char c = 0;
file1.c:
#include "header.h"
file2.c:
#include "header.h"
I was warned about 'duplicate definition' when compiling. I understand the cause as the variable c is defined twice in both file1.c and file2.c; however, I do need to reference the header.h in both c files. How should I overcome this issue?
First, don't define variables in headers. Use the extern qualifier when declaring the variable in the header file, and define it in one (not both) of your C files or in its own new file if you prefer.
header:
extern char c;
implementation:
#include <header.h>
char c = 0;
Alternatively, you can leave the definition in the header but add static. Using static will cause different program behaviour than using extern as in the example above - so be careful. If you make it static, each file that includes the header will get its own copy of c. If you use extern, they'll share one copy.
Second, use a guard against double inclusion:
#ifndef HEADER_H
#define HEADER_H
... header file contents ...
#endif
Use extern char c in your header, and char c = 0 in one of your .c files.
What is char c used for? You probably want it to be extern char c or if you want for this to be a separate variable for each compilation unit(source file) then you should use static char c
If you can't modify the header, then as a hack, in one (but not both) of your source files, you could do this:
#define c d
#include "header.h"
This will result in char c = 0; becoming char d = 0;, but of course, anywhere else that c is used, it will also become d, so it may not work at all.